冒泡排序的時間複雜度O(n)spa
1 var modifiedBubbleSort = function (array) { 2 var length = array.length; 3 var swap = function (index1, index2) { 4 var aux = array[index1]; 5 array[index1] = array[index2]; 6 array[index2] = aux; 7 }; 8 for (var i = 0; i < length; i++) { 9 for (var j = 0; j < length - 1 - i; j++) { 10 if (array[j] > array[j + 1]) { 11 swap(j, j + 1); 12 } 13 } 14 } 15 return array; 16 };
這種實現方法很顯然不管如何都會去比較,所以仍是O(N^2),但這是實現的很差致使的,事實上能夠添加一個標誌位就能夠搞定這個問題:code
1 var modifiedBubbleSort = function (array) { 2 var length = array.length; 3 var swap = function (index1, index2) { 4 var aux = array[index1]; 5 array[index1] = array[index2]; 6 array[index2] = aux; 7 }; 8 for (var i = 0; i < length; i++) { 9 var didSwap = false; 10 for (var j = 0; j < length - 1 - i; j++) { 11 if (array[j] > array[j + 1]) { 12 swap(j, j + 1); 13 didSwap = true; 14 } 15 } 16 if(didSwap == false){ 17 return array; 18 } 19 } 20 }; 21 var result = modifiedBubbleSort(arr);