为什么我的Quicksort程序不能正确排序项目?

时间:2019-04-19 05:30:40

标签: python quicksort

我的快速排序程序正在朝正确的方向更改列表中项目的顺序,但是并没有完全对它们进行排序。

def quick_sort(arr, low, high):
    if (low < high):
        pi = pivot(arr, low, high)
        pivot(arr, low, pi-1)
        pivot(arr, pi+1, high)

def pivot(arr, low, high):
    i = ( low-1 )         
    pivot = arr[high]      

    for j in range(low , high): 

        if   arr[j] <= pivot: 

            i += 1
            arr[i],arr[j] = arr[j],arr[i] 


    arr[i+1], arr[high] = arr[high], arr[i+1] 
    return ( i + 1 ) 
print (numbers)
quick_sort(numbers, 0, len(numbers)-1)
print (numbers)

我希望结果能够正确排序,而不是部分排序。

例如[-9859,-8554,-9846,-9558,-9153,-9483,-7946,-8255,-9743,-8330,-7632,-7513,-7125,1756,-5176,-441,-3385 ,896,-4748,3811,4285,-5883,-4342,6275,5753,585,-2491,-243,-3590,-4377,5986,-3393,-3727,2976,-1532,-3924, 53,-2461,-5882,-1022,2881,-3586,-3191,6153,-4970,-5602,-5944,5528,-3281,1515,-680,-1975,-2472,-4371,- 2574,-5248,-773,-271,-1967,5079,3040,-5871,4825,2810,-2301,1371,315,2911,2669,2477,-3205,-2350,2402,5217,6205, 2593,4595,-4340,6654,7783,9653,8331,8092,6869,7556,9719,8555,9430,8137,9057,8124,7662,6991,6928,7728,7849,7955,7696,7775 / p>

1 个答案:

答案 0 :(得分:1)

我没有详细研究您对pivot的实现(因此可能会有其他问题),但是顶级功能quick_sort有一个明显的问题。您要从中调用pivot三次,但是应该只调用一次,而递归调用quick_sort两次。

尝试:

def quick_sort(arr, low, high):
    if (low < high):
        pi = pivot(arr, low, high)
        quick_sort(arr, low, pi-1)
        quick_sort(arr, pi+1, high)

递归很重要,因为递归的间隔越来越小。您当前的代码有效地将项目分为四个存储桶,但在这些存储桶中,值将按随机顺序排列。