Python 选择排序到zth最高位置

Python 选择排序到zth最高位置,python,algorithm,sorting,selection-sort,Python,Algorithm,Sorting,Selection Sort,我希望实现一种选择排序算法来对未排序的列表/数组进行排序,这是我目前得到的结果: 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] pr

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

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个最高项,应该停止算法)

更新: 我已经尝试过调整交互式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)

我发现了这个python实现

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

对于不太了解algo的人来说,algo不仅会将最大的项目与最后一位进行比较,还会将第二大项目与第二大项目进行比较。这样,我们就能够加快排序算法的速度

希望能有所帮助

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 = z*len(L)
    return comps

好的,使用交互式python示例,我能不能在第一个for循环前面放一个while循环,然后在for循环中有一个计数?然后说,当这个计数小于z值时,算法是什么?
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
def countComps(L, z):
    if z > len(L):
        raise ValueError("List too small")
    comps = z*len(L)
    return comps