n = int(input("Enter no of elements "))
A = []
for i in range(n):
A.append(input())
for i in range(len(A)):
min_idx = i
for j in range(i + 1, len(A)):
if A[min_idx] > A[j]:
min_idx = j
A[i], A[min_idx] = A[min_idx], A[i]
print("Sorted array")
for i in range(len(A)):
print(A[i])
示例输入:
Enter no of elements 4
11
55
22
3
输出:
Sorted array
11
22
3
55
输出中有一个元素保留在未排序位置。代码有什么问题?
答案 0 :(得分:2)
您有缩进错误:
排序代码:
A = [11, 55, 22, 3]
for i in range(len(A)):
min_idx = i
for j in range(i + 1, len(A)):
if A[min_idx] > A[j]:
min_idx = j
A[i], A[min_idx] = A[min_idx], A[i] # <== this line was not indented enough
输出代码:
print("Sorted array")
for i in range(len(A)):
print(A[i])
<强>产地:强>
Sorted array
3
11
22
55
但是,Python很精彩:
Python有一些很好的工具用于此类事情,强烈建议您使用它们。这将提供与上述所有代码相同的输出:
A = [11, 55, 22, 3]
print("Sorted array")
for number in sorted(A):
print(number)
这说明了两件事。