Java0.面试技能源码

快速排序

2019-10-13  本文已影响0人  理想是一盏灯
public static void main(String[] args) {

    int arr[] ={75,70,85,80,60,100,90};
    // 75 70 60 80 85 100 90  ==> 60 70 75 80 85 100 90
    QuickSort(arr,0,6);
    System.out.println(Arrays.toString(arr));
}

public static int [] QuickSort(int arr[],int start,int end){

if(end>start){

    int partition = partition(arr,start,end);

    QuickSort(arr,start,partition-1);
    QuickSort(arr,partition+1,end);

}

return arr;
}

public static int partition(int arr[],int start,int end){

    int prior = arr[start];
    int partition=start;
    int left = start;
    int right = end;

    while(left<right){

        while (right >left && arr[right]>=prior ){
            right--;
        }

        while (left<right  && arr[left] <= prior ){
            left++;
        }

        int temp=arr[right];
        arr[right]=arr[left];
        arr[left]=temp;
    }

    if(start!=left){
        arr[start]=arr[left];
        arr[left] = prior;

        partition=left;
    }

    return partition;
}
上一篇 下一篇

猜你喜欢

热点阅读