排序算法---快速排序
2018-02-24 20:47
211 查看
问题:对 6 1 2 7 9 3 4 5 10 8用快速排序算法将序列由小到大排列
public class Main{
public static void sort(int[] a,int low,int high){
int start = low;
int end = high;
int key = a[low];//基准数(关键字值)
while(end>start){
//从后往前比较
while(end>start&&a[end]>=key) //如果没有比关键值小的,比较下一个,直到有比关键值小的交换位置,然后又从前往后比较
end--;
if(a[end]<=key){
int temp = a[end];
a[end] = a[start];
a[start] = temp;
}
//从前往后比较
while(end>start&&a[start]<=key)//如果没有比关键值大的,比较下一个,直到有比关键值大的交换位置
start++;
if(a[start]>=key){
int temp = a[start];
a[start] = a[end];
a[end] = temp;
}
//此时第一次循环比较结束,关键值的位置已经确定了。左边的值都比关键值小,右边的值都比关键值大,但是两边的顺序还有可能是不一样的,进行下面的递归调用
}
//递归
if(start>low) sort(a,low,start-1);//左边序列。第一个索引位置到关键值索引-1
if(end<high) sort(a,end+1,high);//右边序列。从关键值索引+1到最后一个
}
public static void main(String []args){
int[] a = {12,20,5,16,15,1,30,45,23,9};
int start = 0;
int end = a.length-1;
sort(a,start,end);
for(int i = 0; i<a.length; i++){
System.out.println(a[i]);
}
}
}
public class Main{
public static void sort(int[] a,int low,int high){
int start = low;
int end = high;
int key = a[low];//基准数(关键字值)
while(end>start){
//从后往前比较
while(end>start&&a[end]>=key) //如果没有比关键值小的,比较下一个,直到有比关键值小的交换位置,然后又从前往后比较
end--;
if(a[end]<=key){
int temp = a[end];
a[end] = a[start];
a[start] = temp;
}
//从前往后比较
while(end>start&&a[start]<=key)//如果没有比关键值大的,比较下一个,直到有比关键值大的交换位置
start++;
if(a[start]>=key){
int temp = a[start];
a[start] = a[end];
a[end] = temp;
}
//此时第一次循环比较结束,关键值的位置已经确定了。左边的值都比关键值小,右边的值都比关键值大,但是两边的顺序还有可能是不一样的,进行下面的递归调用
}
//递归
if(start>low) sort(a,low,start-1);//左边序列。第一个索引位置到关键值索引-1
if(end<high) sort(a,end+1,high);//右边序列。从关键值索引+1到最后一个
}
public static void main(String []args){
int[] a = {12,20,5,16,15,1,30,45,23,9};
int start = 0;
int end = a.length-1;
sort(a,start,end);
for(int i = 0; i<a.length; i++){
System.out.println(a[i]);
}
}
}
相关文章推荐
- 排序算法之快速排序
- 排序算法之快速排序
- 简单的排序算法——插入排序,选择排序,交换排序(冒泡排序,快速排序)
- 排序算法——快速排序
- 【排序算法】快速排序原理及Java实现
- 排序算法之快速排序
- 排序算法(3):冒泡排序与快速排序
- 【排序算法】经典排序算法之快速排序
- 常见的排序算法(三) 交换排序(冒泡排序,快速排序)
- 排序算法 之 快速排序
- 排序算法 快速排序
- 八种排序算法Java实现-快速排序
- 必须知道的八大种排序算法【java实现】(一) 冒泡排序、快速排序
- 排序算法(七) —— 快速排序
- 排序算法——快速排序
- 排序算法(选择、希尔、二分插入、冒泡、直接插入、快速排序)
- 排序算法之快速排序
- 排序算法之快速排序 分类: C/C++ 数据结构与算法 2015-06-30 07:59 95人阅读 评论(0) 收藏
- php实现排序算法(一) 冒泡排序 快速排序
- 排序算法(二)- 快速排序