-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathbubble-sort.js
89 lines (81 loc) · 2.6 KB
/
bubble-sort.js
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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
// Custom sorting program in JS via Bubble Sort?
// Time Complexity O(nSquare)
// Space Complexity O(1)
let unSortArr = [4, -1, 34, 9, -9, 103];
const sortArr = (inputArr) => {
var totalIterations = 0;
for (let i = 0; i < inputArr.length; i++) {
totalIterations++
for (let j = i + 1; j < inputArr.length; j++) {
totalIterations++
let temp = inputArr[i];
if (inputArr[i] > inputArr[j]) {
inputArr[i] = inputArr[j];
inputArr[j] = temp;
}
}
}
console.log('arrayLength', inputArr.length);
console.log('totalIterations', totalIterations)
return inputArr;
};
console.log(sortArr(unSortArr));
console.log('---------- Optimize Version ----------')
const sortArrOpt = (inputArr) => {
var totalIterations = 0;
let noSwapsReq;
for (let i = 0; i < inputArr.length; i++) {
totalIterations++
noSwapsReq = true
for (let j = i + 1; j < inputArr.length; j++) {
totalIterations++
let temp = inputArr[i];
if (inputArr[i] > inputArr[j]) {
inputArr[i] = inputArr[j];
inputArr[j] = temp;
noSwapsReq = false
}
}
if (noSwapsReq) break;
}
console.log('arrayLength', inputArr.length);
console.log('totalIterations', totalIterations)
return inputArr;
};
console.log(sortArrOpt(unSortArr));
// Time Complexity: O(nSquare)
function sortArrPlayGround(inputArr, type) {
// Step 1: validations checks
type = type.toLowerCase();
const validSortTypes = ['asc', 'desc'];
if (!Array.isArray(inputArr)) {
return 'Input parameter should be array only.';
}
if (!validSortTypes.includes(type)) {
return 'Sort type should be asc or desc only.';
}
// Step 2: start sorting algo
if(type === 'asc') {
for (let i = 0; i < inputArr.length; i++) {
for(let j = i + 1; j < inputArr.length; j++) {
if(inputArr[i] > inputArr[j]) {
const tempEleVal = inputArr[i]
inputArr[i] = inputArr[j];
inputArr[j] = tempEleVal;
}
}
}
}
if(type === 'desc') {
for (let i = 0; i < inputArr.length; i++) {
for(let j = i + 1; j < inputArr.length; j++) {
if(inputArr[i] < inputArr[j]) {
const tempEleVal = inputArr[i]
inputArr[i] = inputArr[j];
inputArr[j] = tempEleVal;
}
}
}
}
return inputArr;
}