└── index.js /index.js: -------------------------------------------------------------------------------- 1 | /* 2 | -Define a function called bubbleSort that takes an array 3 | -Start looping with a variable called i at the end of the array towards the beginning 4 | -Start an inner loop with a variable called j from the beginning until i-1 5 | -If arr[j] is greater than arr[j+1], swap those two values 6 | -Return the sorted array 7 | */ 8 | 9 | //my solution O(N^2) 10 | function bubbleSort(arr) { 11 | for (let i = arr.length; i > 0; i--) { 12 | for (let j = 0; j < i - 1; j++) { 13 | if (arr[j] > arr[j + 1]) { 14 | // swap indices 15 | [arr[j], arr[j + 1]] = [arr[j + 1], arr[j]]; 16 | } 17 | } 18 | } 19 | return arr; 20 | } 21 | 22 | // Optimize with no swaps O(N) where data is sorted or nearly sorted 23 | function bubbleSort(arr) { 24 | let noSwaps; 25 | for (let i = arr.length; i > 0; i--) { 26 | noSwaps = true; 27 | console.log("ONE ROUND"); 28 | for (let j = 0; j < i - 1; j++) { 29 | if (arr[j] > arr[j + 1]) { 30 | // swap indices 31 | [arr[j], arr[j + 1]] = [arr[j + 1], arr[j]]; 32 | noSwaps = false; 33 | } 34 | } 35 | if (noSwaps) break; 36 | } 37 | 38 | return arr; 39 | } 40 | 41 | console.log(bubbleSort([29, 10, 14, 30, 37, 14, 19])); 42 | console.log(bubbleSort([70, 2, 89, 5, 1, 8, 63, 11])); 43 | console.log(bubbleSort([1, 2, 3, 4, 5, 6])); 44 | --------------------------------------------------------------------------------