八大排序算法之快速排序
八大排序算法每一种都是必须掌握的,不过快速排序是我们必须掌握很熟练并且是面试中被问到的最多次的排序算法。面试时会被面试官问到快速排序实现的原理,会问到给定序列的时间复杂度等等。
快速排序也是分治算法的一种,何为分治算法?请百度,哦不,谷歌一下先。。。Talk is cheap,show you the code!
public class Test9{
/**以下标low对应的元素为基准 将比它小的 排在他的前面 反之排在他的后面 最后返回这个基准元素的下标*/
public static int ThatIndex(int []a, int low,int high){
int tmp = 0;
int thatvalue= a[low];//取出基准元素
while(low < high){
while(low < high && a[high] >= thatvalue ) --high;//找到一个比基准元素小的 停下 和基准值元素交换位置
tmp= a[low];a[low]= a[high];a[high]= tmp;
while(low < high && a[low] <= thatvalue ) ++low;//找到一个比基准元素大的 停下 与基准元素交换位置
tmp= a[low];a[low]= a[high];a[high]= tmp;
}
//最后返回基准元素对应的下标
return low;
}
/**快速排序 递归查找基准元素 把小值放在它的前面 反之放在后面 直到排序完成 结束函数*/
public static void QuickSort(int []a, int low,int high){
if(low < high){
int thatindex= ThatIndex(a, low, high);
QuickSort(a, low, thatindex-1);
QuickSort(a, thatindex+1, high);
}
}
public static void main(String[] args) {
int []a= new int[10];
for (int i = 0; i < a.length; i++) {
Scanner c= new Scanner(System.in);
a[i]= c.nextInt();
}
QuickSort(a, 0, a.length-1);
for (int i : a) {
System.out.print(i+" ");
}
}
}