快速排序JAVA实现
package kpp.sort; /** * 快速排序 * 一般选取首元素为枢轴元素,保存至pivot,确定头尾指针left,right, * 先对整个数组元素进行排序,此时枢轴元素两侧元素有序,再分别对枢轴元素两侧的两个数组执行排序 * 排序规则 * 1.right指针从右向左遍历,如果比当前枢轴元素pivot小,则将data[right]赋给data[left] * 2.left指针从左向右遍历,如果比当前枢轴元素pivot大,则将data[left]赋给data[right] * 3.当left和right指针走到一起时,比如index,则将pivot赋给data[index] * * @author kpp * */ public class QuickSort { public static void main(String[] args) { // TODO Auto-generated method stub int array[] = {49,38,65,97,176,213,227,49,78,34,12,164,11,18,1}; quickSort(array, 0, array.length - 1); for (int i = 0; i < array.length; i++) { System.out.print(array[i]+" "); } } private static int quickSort(int data[],int left,int right){ int pivot; if(left < right){ pivot = sort(data,left,right); System.out.println(pivot); quickSort(data,left,pivot-1); quickSort(data,pivot+1,right); } return 0; } private static int sort(int data[],int left,int right){ int pivot = data[left]; while(left < right){ while(left < right&&data[right] >= pivot){ right--; } data[left]=data[right]; while(left < right&&data[left] <= pivot){ left++; } data[right]=data[left]; } //left==right时,证明祠堂排序完毕,将枢轴元素赋给data[left] data[left] = pivot; return left; } }