-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathbubbleSort.js
More file actions
51 lines (39 loc) · 1.24 KB
/
bubbleSort.js
File metadata and controls
51 lines (39 loc) · 1.24 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
// Time Complexity - O(n * 2)
// Space Complexity - O(1) --> We are not creating any datastructure
// [99, 44, 6, 2, 1, 5, 63, 87, 283, 4, 0];
// [44, 99, 6, 2, 1, 5, 63, 87, 283, 4, 0]; --> New Array -> 1st Step
// [44, 6, 99, 2, 1, 5, 63, 87, 283, 4, 0]; --> New Array -> 1st Step
// [6, 44, 99, 2, 1, 5, 63, 87, 283, 4, 0]; --> New Array -> 1st Step
const bubbleSort = (arr) => { // [99, 44, 6, 2, 1, 5, 63, 87, 283, 4, 0];
for(let i = 1; i < arr.length; i++) {
if(arr[i] < arr[i - 1]) {
// Using Third Variable
let temp = arr[i];
arr[i] = arr[i - 1];
arr[i - 1] = temp;
}
}
for(let i = 1; i < arr.length; i++) {
if(arr[i] < arr[i - 1]) {
bubbleSort(arr);
}
}
return arr;
}
// Bubble sort -->
// 1. Nested Loop
const bubbleSortNestedLoop = (arr) => {
for(let i = 0; i < arr.length; i++) {
for(let j = i + 1; j < arr.length; j++) {
if(arr[i] >= arr[j]) {
let temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
}
return arr;
}
const arr = [99, 44, 6, 2, 1, 5, 63, 87, 283, 4, 0];
console.log(bubbleSort(arr));
console.log(bubbleSortNestedLoop(arr));