所以我有两个泡泡分类:1个来自演讲幻灯片,另一个是我自己写的:
def lecture_bubble(L):
while True:
swapped = False
for i in range(len(L) -1):
if L[i] > L[i+1]:
L[i+1] ,L[i] = L[i], L[i+1]
swapped = True
if not swapped:
# No swaps this pass ; therefore sorted
return L
def bubble_sort(array):
for i in range(len(array)-1):
swapped = False
for j in range(len(array)-1,i,-1):
if array[j] < array[j-1]:
array[j], array[j-1] = array[j-1], array[j]
swapped = True
if not swapped:
return array
return array
比较两者:
Time taken for lecture_bubble is 4.485383749008179
Time taken for bubble_sort is 0.00061798095703125
[Finished in 4.6s]
有人可以解释为什么我的bubble_sort排序数组的时间要少得多吗?
我的泡泡也可以进一步改进吗?
答案 0 :(得分:0)
教授代码执行到#34;如果没有交换&#34;是真的。你的任务将执行到#34; for循环的结束&#34;或者&#34;如果没有交换&#34;。在某些情况下,您的代码可能无效。
答案 1 :(得分:0)
Professor的算法一旦遍历所有元素而不进行任何交换就停止排序-这意味着该数组已排序。下面用Javascript编写了相同的算法
将每个对象与邻居进行比较,如果第一个大于下一个,则进行交换
function bubbleSort(arr){
console.log("Input Array");
console.log(arr);
let i = 0
let temp;
let notSorted;
do {
notSorted = false;
for (let j = 0; j < arr.length-i; j++) {
if (arr[j] > arr[j+1]) {
notSorted = true;
temp = arr[j];
arr[j] = arr[j+1];
arr[j+1] = temp;
console.log(arr[j],"swapped with",arr[j+1])
console.log(arr);
} else {
console.log("SKIP");
}
console.log(j, arr.length-i);
}
i++;
} while (notSorted)
console.log("Sorted using Bubble Sort");
return arr;
}
// console.log(bubbleSort([1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20])); // uncomment to run and see how efficient this algorithm is when array is sorted
console.log(bubbleSort([5,8,18,4,19,13,1,3,2,20,17,15,16,9,10,11,14,12,6,7]));