选择排序到第zth个最高位置

2024-09-27 21:29:14 发布

您现在位置:Python中文网/ 问答频道 /正文

我希望实现一个选择排序算法来对未排序的列表/数组进行排序,这是我目前得到的结果:

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]

Tags: 项目in算法forlenif排序count
2条回答
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

当然,既然你只关心增加薪酬:

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

我发现这个python实现

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

对于那些不太了解algo的人来说,它不仅会比较,还会把最大的项目放在最后一位,把第二大的项目放在第二大的位置。这样,我们就可以提高排序算法的速度。你知道吗

希望能有所帮助。你知道吗

相关问题 更多 >

    热门问题