Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/algorithm/10.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 使用重复元素的简单选择排序?_Python_Algorithm_Sorting - Fatal编程技术网

Python 使用重复元素的简单选择排序?

Python 使用重复元素的简单选择排序?,python,algorithm,sorting,Python,Algorithm,Sorting,给定一个列表x,我想使用选择排序对其进行排序,然后计算排序中进行的交换数量。所以我得出了这样的结论: count=0 a=0 n=len(x) while (n-a)>0: #please recommend a better way to swap. i = (min(x[a:n])) x[i], x[a] = x[a], x[i] a += 1 #the count must still be there count+=1 print (

给定一个列表
x
,我想使用选择排序对其进行排序,然后计算排序中进行的交换数量。所以我得出了这样的结论:

count=0
a=0
n=len(x)
while (n-a)>0:
    #please recommend a better way to swap.
    i = (min(x[a:n]))
    x[i], x[a] = x[a], x[i]
    a += 1
    #the count must still be there
    count+=1
print (x)

你能帮我找到一个更好的办法吗?它没有那么好用。

问题不在于重复的元素。您的代码也不适用于所有元素都不同的列表。尝试
x=[2,6,4,5]

i = (min(x[a:n]))

min()。您的代码也不适用于所有元素都不同的列表。尝试
x=[2,6,4,5]

i = (min(x[a:n]))

min()。必须使用索引来标识位置

seq = [2,1,0,0]
beg = 0
n = len(seq)

while (n - beg) > 0:
    jdx = seq[beg:n].index((min(seq[beg:n])))            # use the remaining unsorted right
    seq[jdx + beg], seq[beg] = seq[beg], seq[jdx + beg]  # swap the minimum with the first unsorted element.
    beg += 1

    print(seq)

print('-->', seq)
  • 随着排序的进行,列表[0:beg]的左侧将被排序,右侧的[beg:]将被排序,直到完成
  • jdx是列表剩余部分中最小值的位置(索引)(查找最小值必须发生在列表未排序的右侧部分-->[beg:])

您混淆了元素的值及其位置。必须使用索引来标识位置

seq = [2,1,0,0]
beg = 0
n = len(seq)

while (n - beg) > 0:
    jdx = seq[beg:n].index((min(seq[beg:n])))            # use the remaining unsorted right
    seq[jdx + beg], seq[beg] = seq[beg], seq[jdx + beg]  # swap the minimum with the first unsorted element.
    beg += 1

    print(seq)

print('-->', seq)
  • 随着排序的进行,列表[0:beg]的左侧将被排序,右侧的[beg:]将被排序,直到完成
  • jdx是列表剩余部分中最小值的位置(索引)(查找最小值必须发生在列表未排序的右侧部分-->[beg:])

您不使用
x.sort()
有什么原因吗?我实际上计划添加一个“计数”功能,它将跟踪列表中两个数字的次数。因此,我必须手动执行此操作。计数已经固定,所以不用担心。您不使用
x.sort()
有什么原因吗?我实际上计划添加一个“计数”功能,它将跟踪列表交换中两个数字的多少倍。所以我必须手动操作。计数已经被修正,所以不用担心。谢谢这里的帮助。现在可以了。可能其中的一个变化是将列表作为索引,我们只选择没有排序元素的部分。谢谢这里的帮助。现在可以了。可能其中的一个变化是我们将列表作为索引,我们只选择没有排序元素的部分。感谢澄清,我现在得到了差异。感谢澄清,我现在得到了差异。