HackerRank:我的QuickSort算法太慢

时间:2018-11-06 20:10:33

标签: java algorithm quicksort

有人可以向我解释为什么这种QuickSort算法的性能不好吗?

我遵循了Derek Banas的教程,因此我认为这是最佳选择。

public static void quickSort(int[] arr, int left, int right){
    if(left>=right) return;
    int pivot = arr[right];
    int index = partition(arr, left, right, pivot);
    quickSort(arr, left, index-1);
    quickSort(arr, index+1, right);
}

private static int partition(int[] arr, int left, int right, int pivot){
    int leftPointer = left-1;
    int rightPointer = right;
    while(true){
        while(arr[++leftPointer]<pivot && leftPointer<=rightPointer); 
        while(arr[--rightPointer]>pivot && rightPointer>leftPointer); 
        if(leftPointer>=rightPointer) break;
        else{
            //swap values
            int temp = arr[leftPointer];
            arr[leftPointer] = arr[rightPointer];
            arr[rightPointer] = temp;
        }
    }
    int tempP = arr[leftPointer];
    arr[leftPointer] = arr[right];
    arr[right] = tempP;
    return leftPointer;

}

0 个答案:

没有答案