1bubbleSort(Array) {
2 let len = Array.length;
3 for (let i = 0; i < len; i++) { //you can also use "for in", so you don't need the variable "len"
4 for (let j = 0; j < len; j++) {
5 if (Array[j] > Array[j + 1]) {
6 let tmp = Array[j];
7 Array[j] = Array[j + 1];
8 Array[j + 1] = tmp;
9 }
10 }
11 }
12 return Array;
13};
1const bubbleSort = array => {
2 const arr = Array.from(array); // avoid side effects
3 for (let i = 1; i < arr.length; i++) {
4 for (let j = 0; j < arr.length - i; j++) { // starts up to length - 1
5 if (arr[j] > arr[j + 1]) {
6 [arr[j], arr[j + 1]] = [arr[j + 1], arr[j]];
7 }
8 }
9 }
10 return arr;
11};
12
13console.log(bubbleSort([4, 9, 2, 1, 5]));
14
1const bubbleSort = (arr) => {
2 for (let i = 0; i < arr.length; i++) {
3 for (let j = 0; j < arr.length - i; j++) {
4 if (arr[j] > arr[j + 1]) {
5 let tmp = arr[j];
6 arr[j] = arr[j + 1];
7 arr[j + 1] = tmp;
8 }
9 }
10 }
11 return arr;
12}
1function bubblesort(array) {
2 len = array.length;
3
4 for (let i = 0; i < len; i++) {
5 for (let j = 0; j < len - i; j++) {
6 let a = array[j];
7 if (a != array[-1]) {
8 var b = array[j + 1];
9 if (a > b) {
10 array[j] = b;
11 array[j + 1] = a;
12 }
13 }
14 }
15 }
16}
17
18let array = [10, 9, 8, 7, 6, 5, 4, 3, 2, 1];
19bubblesort(array);
20console.log(array)
1function BubbleSort(arr) {
2 const sortedArray = Array.from(arr);
3 let swap;
4 do {
5 swap = false;
6 for (let i = 1; i < sortedArray.length; ++i) {
7 if (sortedArray[i - 1] > sortedArray[i]) {
8 [sortedArray[i], sortedArray[i - 1]] = [sortedArray[i - 1], sortedArray[i]];
9 swap = true;
10 }
11 }
12 } while (swap)
13 return sortedArray;
14 }
15
16 console.log(BubbleSort([7,99,1,88,34,2,90,7]));
1// like using Array.reverse();
2function bubbleReverse(arr) {
3 for (let i = arr.length - 1; i > 0; i--) {
4 for (let j = arr.length - 1; j > 0; j--) {
5 if (arr[j] > arr[j - 1]) {
6 let temp = arr[j];
7 arr[j] = arr[j - 1];
8 arr[j - 1] = temp;
9 }
10 }
11 }
12 return arr;
13}
14
15// like using Array.sort();
16function bubbleSort(arr) {
17 for (let i = 0; i < arr.length - 1; i++) {
18 for (let j = 0; j < arr.length - 1; j++) {
19 if (arr[j] > arr[j + 1]) {
20 let temp = arr[j];
21 arr[j] = arr[j + 1];
22 arr[j + 1] = temp;
23 }
24 }
25 }
26 return arr;
27}