尝试编写一个解决方案来重新排序数组而不使用sort()



我觉得我很接近,但不太确定为什么我的while循环停止执行,我希望它运行/增加计数器然后条件为真,然后当它遇到数字乱序时,交换它们,然后减少计数器,然后再次运行while循环,直到所有的数字都是有序的。就像它把打乱顺序的数字向后滑动直到它比它前面的数字高,但比它后面的数字低。如果这说得通的话。可能对你们大多数人来说很简单,但我只是刚接触python。下面是我到目前为止的代码;

arr = [7, 14, 21, 32, 17, 48, 69, 78, 72]
count = 0
while (count < len(arr) - 1) and (arr[count] < arr[count+1]):
count += 1
if (arr[count] > arr[count+1]):
arr[count], arr[count+1]  = arr[count+1], arr[count]
count -= 1
continue
print(count)
print(arr)

在我的代码下面加上一些伪代码使它更清晰。

# list of numbers out of order
arr = [7, 14, 21, 32, 17, 48, 69, 78, 72]
# first position in index
count = 0
# loop to check first if value of index position is less than length of array -1 (9-1 = 8) 
# or if value of index position is less than index position + 1 (next index position)
while (count < len(arr) - 1) and (arr[count] < arr[count+1]):
# if true loop should continue + 1 on the next index
count += 1
# if the value of number in the current index position is greater than the next number it swaps them.
if (arr[count] > arr[count+1]):
arr[count], arr[count+1]  = arr[count+1], arr[count]
count -= 1
continue
print(count)


print(arr)

我已经尝试了各种不同的东西,我想我只是卡住了while循环的实际工作方式,我需要让循环在它命中第一个错误语句后再次运行。

这将以问题所要求的方式工作:

  • 查找前两个顺序错误的数字。
  • 只切换这些数字并退出。
arr = [7, 14, 21, 32, 17, 48, 69, 78, 72]

for i, v in enumerate(arr):
if i == len(arr) -1:
print('reached the end')
break
if v > arr[i+1]:
print('out of order index', i, 'value:',v)
# do the switch
arr[i], arr[i+1] = arr[i+1], v
break

print(arr)

结果如下:

out of order index 3 value: 32
[7, 14, 21, 17, 32, 48, 69, 78, 72]

只要存在break条件,您也可以对while loop实现相同的操作。

最新更新