【问题标题】:Recursive Selection Sort递归选择排序
【发布时间】:2015-02-13 00:18:09
【问题描述】:

我正在尝试编写递归选择排序,我真的很困惑,而且很难追踪为什么这不起作用。如果有人能告诉我问题出在哪里,那就太好了!

这是我的代码

def selectionSortRecursive(lis, minIndex = 0):
    if minIndex - 1 == len(lis):
        return lis
    minValueIndex = minIndex #Assigns the very first item in the list as the minimum value index
    for i in range (minIndex + 1, len(lis)):
        if lis[i] < lis[minValueIndex]: #if any item is less than min value, its index gets assigned the minimum value
            minValueIndex = i
    lis[minIndex], lis[minValueIndex] = lis[minValueIndex], lis[minIndex] #After you go through the list, you switch the smallest item into the minimum index, which starts off being 0
    lis = selectionSortRecursive(lis, minIndex+1) #now we're gonna sort the list at the next min
    return lis

【问题讨论】:

    标签: sorting recursion selection-sort


    【解决方案1】:

    请试试这个修改:

    def selectionSortRecursive(lis, minIndex = 0):
        if minIndex - 1 == len(lis):
            return lis
        minValueIndex = minIndex #Assigns the very first item in the list as the minimum value index
        for i in range (minIndex + 1, len(lis)):
            if lis[i] < lis[minValueIndex]: #if any item is less than min value, its index gets assigned the minimum value
                lis[minValueIndex], lis[i] = lis[i], lis[minValueIndex] #After you go through the list, you switch the smallest item into the minimum index, which starts off being 0
        lis = selectionSortRecursive(lis, minIndex+1) #now we're gonna sort the list at the next min
        return lis
    

    【讨论】:

      【解决方案2】:

      试试这个。

      static int maxIndex;
          public static void selectionSort(Object[] source, int fromIndex, int endIndex){
              if(endIndex==fromIndex){
                  return;
              }
              else{
                  if(((Comparable) source[fromIndex]).compareTo(source [maxIndex])>0){
                      maxIndex=fromIndex;
                  }
                  bubbleSort(source,fromIndex+1,endIndex);
              }
              Object temp=source[fromIndex];
              source[fromIndex]=source[maxIndex];
              source[maxIndex]=temp;
              bubbleSort(source,fromIndex,endIndex-1);
          }
      

      【讨论】:

        猜你喜欢
        • 2015-08-13
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-01-16
        • 2018-11-26
        • 2019-05-09
        • 2019-03-09
        • 2013-12-27
        相关资源
        最近更新 更多