【代码积累】quick sort

来源:互联网 发布:詹姆斯13年总决赛数据 编辑:程序博客网 时间:2024/05/07 03:34
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*///此处选择二分法选择pivotint 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;}}

原创粉丝点击