快速排序 -- java实现

来源:互联网 发布:淘宝性用品什么分类 编辑:程序博客网 时间:2024/06/14 00:57

思想:

采用分治策略。

每次排序会使一个元素落在最终位置,并且该元素之前的数据都比不比它大,之后的元素都不比它小。

然后再对前后两部分分别进行快排。


每一轮排序的思想:

选定一个元素为比较标准pivot,

  • 从后往前找到第一个比它小的元素,并将该元素放在最小下标位置,最小下标++;
  • 从前往后找到第一个比它大的元素,并将该元素放在最大下标位置,最大下标--;
  • 将pivot复制给最小下标值。

代码:


public static void quickSort(int a[] , int low ,int high){int pivot;if(low < high){pivot = partition(a,low,high);quickSort(a,low,pivot-1);quickSort(a,pivot+1,high);}}public static int partition(int a[] , int low ,int high){int pivotValue = a[low];int tmp;while(low<high){//从后边找到第一个比pivotValue小的while(low<high && pivotValue<a[high]){high--;}if(low<high){//将找到的小值赋给a[low],并将low++a[low++] = a[high];}//从前边找到第一个比pivotValue大的while(low<high && pivotValue > a[low]){low++;}if(low<high){a[high--] = a[low];}}a[low]=pivotValue;return low;}public static void main(String []args){int b[] = {5,3,12,5,4,78,6,10,33};for(Integer i : b){System.out.print(i +",");}quickSort(b, 0, b.length-1);System.out.println("\n快排后:");for(Integer i : b){System.out.print(i+",");}}


运行结果:




第一遍排序,草图:



1 0
原创粉丝点击