[英]Cant seem to figure out what Sorting Algorithm I have written
We recently stared doing sorting algorithms in school. 我们最近开始在学校盯着排序算法。 So I wrote the code below, it works but I don't know whether it is Bubble sort or Selection Sort.
所以我写了下面的代码,它可以工作,但是我不知道它是冒泡排序还是选择排序。
for i in range(0 , len(array)):
for j in range(0 , len(array) -1):
if (array[j] > array[j +1]):
array[j] , array[j + 1] = array[j + 1] , array[j]
Algorithm: Bubble Sort
算法:
Bubble Sort
Because it repeatedly swaps the adjacent elements if they are in the wrong order. 因为如果相邻元素顺序错误,它将重复交换相邻元素。
for i in range(0 , len(array)):
for j in range(0 , len(array) - i -1):
# traverse the array from 0 to len(array) - i - 1
# Swap if the element found is greater
# than the next element
if (array[j] > array[j +1]):
array[j] , array[j + 1] = array[j + 1] , array[j]
There is an error in your second for loop, you need to traverse it to len(array) -i -1
, because at the end of each iteration largest element would be at the end of the array. 第二个for循环中有一个错误,您需要将其遍历到
len(array) -i -1
,因为在每次迭代结束时,最大的元素将在数组的末尾。
Hope this answers your question!! 希望这能回答您的问题!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.