【问题标题】:Quick Sort Algorithm using python使用python的快速排序算法
【发布时间】:2020-09-11 00:26:21
【问题描述】:

我将第一个元素作为起始值和枢轴值。
当枢轴小于结束值时增加起始位置。
当枢轴大于结束值时减少结束位置。
此外,每次通过完成时交换开始和结束位置。
如果起始位置与结束位置交叉,那么我将交换枢轴和结束元素。

def partition(arr, lb, ub):
  pivot = arr[lb]  
  start = lb
  print('start', start)
  end = ub
  print('end', end)
  while start <= end:

    while arr[start] <= pivot:
          start += 1
    while arr[end] >= pivot:
          end -= 1
    if start <= end:
      arr[start], arr[end] = arr[end], arr[start]
    else:
      arr[end], arr[lb] = arr[lb], arr[end]
    return end 

def quickSort(arr, lb, ub): 
    if lb >= ub:
      return 0
    loc = partition(arr, lb, ub)
    quickSort(arr, lb, loc-1) 
    quickSort(arr, loc+1, ub) 

arr = [10, 4, 7, 3, 8, 6, 9, 1, 5, 2] 

n = len(arr)
print(n)
quickSort(arr, 0, len(arr) -1) 
print ("Sorted array is:") 
for i in range(n): 
    print("%d" % arr[i])

我收到以下错误: 索引错误

---> quickSort(arr, 0, len(arr) -1)

Error in partition(arr, lb, ub)

---> while arr[start] <= pivot:


IndexError: list index out of range 

谁能告诉我这段代码有什么问题?

【问题讨论】:

    标签: python python-3.x algorithm sorting quicksort


    【解决方案1】:

    这是错误的直接原因:

        while arr[start] <= pivot:
              start += 1
        while arr[end] >= pivot:
              end -= 1
    

    您不检查start 是否不大于ub(以及end 是否不小于lb)。这是你应该做的:

            while start < ub and arr[start] <= pivot:
                start += 1
            while end > lb and arr[end] >= pivot:
                end -= 1
    

    但是,还有一点不对:

        while start <= end:
    

    应该是

        while start < end:
    

    因为对于弱不等式,循环永远不会结束——它会达到start == end 的状态并在那里无限循环。这里的不等式:

           if start <= end:
    

    也应该是一个强大的,否则对于start == end,您将用arr[start](即它自己)而不是arr[lb](即枢轴)交换arr[end]

    最后,您在此处发布的代码格式有问题,所以我冒昧地对其进行了修复。

    【讨论】:

      【解决方案2】:

      不确定您是否还没有解决方案,但这里有一个修改后的分区函数。

      def partition(arr, lb, ub):
        pivot = arr[lb]
        start = lb + 1
        print('start', start)
        end = ub
        print('end', end)
        while start <= end:
          while start <= end and arr[start] <= pivot:
            start += 1
          while end >= start and arr[end] > pivot:
            end -= 1
          if start < end:
            arr[start], arr[end] = arr[end], arr[start]
        if start >= end:
          start -= 1
        arr[start], arr[lb] = arr[lb], arr[start]
        return start
      

      【讨论】:

        【解决方案3】:

        您需要检查start的增量是否不超过end,如下所示,

        while arr[start] <= pivot:
            if start<end:
                  start += 1
        

        【讨论】:

        • 这行不通,因为您在检查start 是否不是太大之前访问了arr[start]
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-08-01
        • 1970-01-01
        • 2017-02-27
        • 2016-11-24
        • 2018-05-17
        • 1970-01-01
        相关资源
        最近更新 更多