-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbubbleSort.js
More file actions
40 lines (35 loc) · 739 Bytes
/
Copy pathbubbleSort.js
File metadata and controls
40 lines (35 loc) · 739 Bytes
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
//We are passing arr as reference we do not need a return statement
//and we modifying
function bubbleSort(arr){
var sorted = false;
while(!sorted){
sorted = true;
for(let i = 0; i < arr.length; i++){
if(arr[i]> arr[i+1]){
var temp = arr[i];
arr[i] = arr[i+1];
arr[i+1] = temp;
sorted = false;
}
}
}
return arr;
}
var arr = [4,9,1,6,3]
console.log(bubbleSort(arr))
console.log(arr)
//USING TWO LOOPS
function bubbleSortII(arr){
for(let i = 0; i < arr.length; i++){
for( let j = 0; j < arr.length; j++){
if(arr[i]> arr[i+1]){
var temp = arr[i];
arr[i] = arr[i+1];
arr[i+1] = temp;
}
}
}
}
console.log(bubbleSortII(arr))
console.log("using two for loops")
console.log(arr)