基于median3和cutoff值选择快速排序和插入排序

152 阅读1分钟
public class standQuickSort1 {


    public static void main(String[] args) {
        int[] arr = {9, 8, 7, 6, 5, 4, 3, 2, 1,0};
        quickSort(arr,0,arr.length-1, 3);
        System.out.println(Arrays.toString(arr));
    }

    public static void swap(int[] arr,int i,int j) {
        int temp = arr[i];
        arr[i] = arr[j];
        arr[j]=temp;
    }
    public static int median3(int[] arr,int left,int right) {
        int mid=(left+right)/2;
        if (arr[left] > arr[mid]) {
            swap(arr,left,mid);
        }if (arr[left] > arr[right]) {
            swap(arr,left,right);
        }if (arr[mid] > arr[right]) {
            swap(arr,mid,right);
        }
        swap(arr,mid,right-1);
        return arr[right];
    }

    public static void quickSort(int[] arr,int left,int right,int cutoff) {
        if (right - left > cutoff) {
            int pivot = median3(arr, left, right);
            int i=left;
            int j=right-1;
            for (; ; ) {
                while (arr[++i] < pivot) {
                }
                while (arr[--j] > pivot) {
                }
                if (i < j) {
                    swap(arr, i, j);
                } else {
                    break;
                }
            }
            swap(arr, i, right - 1);
            quickSort(arr,left,i-1,cutoff);
            quickSort(arr,i+1,right,cutoff);
        } else {
            for (int i = 1; i <arr.length ; i++) {
                int insertVal = arr[i];
                int insertIndex=i-1;
                while (insertIndex >= 0 && arr[insertIndex] > insertVal) {
                    arr[insertIndex + 1] = arr[insertIndex];
                    insertIndex--;
                }
                arr[insertIndex+1]=insertVal;
            }
        }


    }
}