import java.awt.image.PixelInterleavedSampleModel; public class Main { public static void main(String[] args) { // TODO Auto-generated method stub //int[] test = {5,4,3,2,1}; int[] test={49,38,65,97,76,13,27,49,78,34,12,64,5,4,62,99,98,54,56,17,18,23,34,15,35,25,53,51}; quickSort(test,0,test.length-1); for(int i=0;i<test.length;i++) { System.out.format("%d ", test[i]); } System.out.format("\r"); } public static void quickSort(int[] a,int left,int right) { //left,right是下标 if( left >= right ) { return; } /*选出pivot的index作为参考,根据pivot对原数组进行划分,再分别对左右子数组递归调用quickSort*/ //此处选择二分法选择pivot int pivotIndex = (left+right)/2; //调用partition,根据pivotValue对数组进行重排 int regroupIndex = partition(a,left,right,pivotIndex); // for(int i=0;i<a.length;i++) { // System.out.format("%d ", a[i]); // } // System.out.format("\r"); quickSort(a, left, regroupIndex-1); quickSort(a, regroupIndex+1, right); } public static int partition(int[] a,int left,int right,int pivotIndex) { int pivotValue = a[pivotIndex]; int tmp = 0; //用来swap //将pivotValue移动到数组尾 tmp = pivotValue; a[pivotIndex] = a[right]; a[right] = pivotValue; //逐个遍历 [left,right-1]的元素,将比pivotValue小的元素尽量往前放,同时storeIndex递增,最终storeIndex就是pivotValue该放的位置(storeIndex右边都是比pivotValue大的元素) int storeIndex = left; for(int i=left;i<=right-1;i++) { //这里的left,right是实际的下标 if( a[i] < pivotValue ) { //交换a[i]和a[storeIndex],storeIndex递增 tmp = a[i]; a[i] = a[storeIndex]; a[storeIndex] = tmp; storeIndex++; } } //比较结束,比pivotValue小的元素都在 storeIndex的左边,大的元素在右边,交换a[storeIndex]与a[right] tmp = a[storeIndex]; a[storeIndex] = a[right]; a[right] = tmp; return storeIndex; } }