首页 文章

选择排序到第z个最高位置python

提问于
浏览
0

我正在寻求实现一个选择排序算法来排序未排序的列表/数组,这是我目前得到的:

list1 = [14,3,2,21,23,12,3,4]#unsorted array
z = 3
for i in range(len(list1)):
    for j in range(i, len(list1)):
        if list1[i] < list1[j]:     
            list1[i], list1[j] = list1[j], list1[i]

print(list1)

我面临的问题是获得第z项最高分 . 即,打印最高项目直到索引z

所以应该打印:

[23,21,14]

它应该返回项目比较的数量(但必须是选择排序算法) . 并且不应该进行比它需要的比较(应该在找到第z个最高项后停止算法)

更新:我已经尝试调整交互式python实现......我只是无法理解它

这就是我所拥有的

def selectionSort(alist, k):
    count = 0
    while count < k:
        for fillslot in range(len(alist)-1,0,-1):
            print(count)
            count += 1
            positionOfMax = 0
            for location in range(1,fillslot+1):
                if alist[location] < alist[positionOfMax]:
                    positionOfMax = location

            temp = alist[fillslot]
            alist[fillslot] = alist[positionOfMax]
            alist[positionOfMax] = temp

alist = [54,26,93,17,77,31,44,55,20]
selectionSort(alist , 3)
print(alist)

这打印:

0
1
2
3 # should it not stop here since count is less than k?
4
5
6
7
[93, 77, 55, 54, 44, 31, 26, 20, 17]

2 回答

  • 0
    import itertools
    
    def limitedInsertionSort(L, z):
        comps = 0
        if z > len(L):
            raise ValueError("List too small")
        for i,j in itertools.product(range(z), range(len(L))):
            if L[i] < L[j]:
                L[i], L[j] = L[j], L[i]
            comps += 1
        return comps
    

    但当然,因为你只关心增加comps:

    def countComps(L, z):
        if z > len(L):
            raise ValueError("List too small")
        comps = 0
        for i,j in itertools.product(range(z), range(len(L))):
            comps += 1
        return comps
    

    但是,既然你知道增加 comps 的次数,你可以做乘法:

    def countComps(L, z):
        if z > len(L):
            raise ValueError("List too small")
        comps = z*len(L)
        return comps
    
  • 0

    我找到了这个python实现

    http://interactivepython.org/runestone/static/pythonds/SortSearch/TheSelectionSort.html

    对于那些不太了解算法的人来说,它不仅要比较,而且还要将最大的项目放在最后一个位置,将第二大项目放在第二大位置 . 这样做,我们就能够加快排序算法的步伐 .

    希望它可能有所帮助 .

相关问题