【代码积累】quick sort bia direction

来源:互联网 发布:詹姆斯13年总决赛数据 编辑:程序博客网 时间:2024/05/19 18:13
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};quickSortBia(test,0,test.length-1,false);showArray(test);}public static void showArray(int[] a) {for(int i=0;i<a.length;i++) {System.out.format("%d ", a[i]);}System.out.format("\r");}/*low and high are index of the elements in the array*/public static void quickSortBia(int[] a,int low,int high,boolean isAscend) {if( low >= high ) {return;}//calculate pivot indexint pivotIndex = (low+high)/2;int storeIndex = partition(a,low,high,pivotIndex,isAscend);quickSortBia(a,low,storeIndex-1,isAscend);quickSortBia(a,storeIndex+1,high,isAscend);}public static int partition(int[] a,int low,int high,int pivotIndex,boolean isAscend) {int pivotValue = a[pivotIndex];int storeIndex = low; //This is the key stepint tmp = 0;//swap a[pivotIndex] and a[high]a[pivotIndex] = a[high];a[high] = pivotValue;/*traverse from a[0] to a[high-1] in a loop,the storeIndex start from 0,and each time a[i] is smaller/larger than pivotValue  * swap a[i] and a[storeIndex],increase storeIndex by 1,after the loop,swap a[high] and a[storeIndex],return storeIndex.*/for(int i=low;i<=high-1;i++) {if( true == isAscend ) {if(a[i] < pivotValue) {tmp = a[i];a[i] = a[storeIndex];a[storeIndex] = tmp;storeIndex++;  //increase after swap a[i] and a[storeIndex]}}else {if(a[i] > pivotValue) {tmp = a[i];a[i] = a[storeIndex];a[storeIndex] = tmp;storeIndex++;}}}tmp = a[storeIndex];a[storeIndex] = pivotValue;a[high] = tmp;showArray(a);return storeIndex;}}/*综述: * 快速排序的几个关键点: * 1、分治法,参照点的选取方式 * 2、partition函数的作用是对根据pivot对数列进行趋势排列,然后根据pivot的最终index,将数列划分为2个子数列,再对子数列进行排序,递归调用 *    partition的storeIndex的值取数列的首坐标,不能初始化为0 *    partition中有3次swap *    只有在发生了a[i] 与 a[storeIndex]的交换后,才需要对storeIndex进行递增操作 *    */