Skip to content
This repository was archived by the owner on Jun 2, 2024. It is now read-only.

Commit 7d7b56c

Browse files
Add Comb Sort Algorithm in Javascript/Algorithms (#939)
1 parent 560565a commit 7d7b56c

File tree

1 file changed

+63
-0
lines changed

1 file changed

+63
-0
lines changed

Javascript/Algorithms/comb-sort.js

Lines changed: 63 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,63 @@
1+
/**
2+
* Time Complexity:
3+
* O(n^2), where n is the length of the input array.
4+
5+
* Space Complexity:
6+
* O(1), as sorting happens in-place in comb-sort.
7+
**/
8+
9+
/**
10+
* @param {number[]}
11+
* @return {number[]}
12+
*/
13+
const combSort = arr => {
14+
/**
15+
* @param {number[]}
16+
* @return {boolean}
17+
*/
18+
const isArraySorted = arr => {
19+
for (let i = 0; i < arr.length - 1; i++) {
20+
if (arr[i] > arr[i + 1]) return false;
21+
}
22+
return true;
23+
};
24+
25+
let iterationCount = 0;
26+
let gap = arr.length - 2;
27+
let decreaseFactor = 1.25;
28+
29+
// Repeat iterations Until array is not sorted
30+
31+
while (!isArraySorted(arr)) {
32+
// If not first gap Calculate gap
33+
if (iterationCount > 0) {
34+
if (gap != 1) {
35+
gap = Math.floor(gap / decreaseFactor);
36+
}
37+
}
38+
// Set front and back elements and increment to a gap
39+
let front = 0;
40+
let back = gap;
41+
while (back <= arr.length - 1) {
42+
// Swap the elements if they are not ordered
43+
if (arr[front] > arr[back]) {
44+
let temp = arr[front];
45+
arr[front] = arr[back];
46+
arr[back] = temp;
47+
}
48+
49+
// Increment and re-run swapping
50+
front += 1;
51+
back += 1;
52+
}
53+
iterationCount += 1;
54+
}
55+
return arr;
56+
};
57+
58+
let arr = [3, 0, 2, 5, -1, -2, -1, 4, 1];
59+
60+
console.log("Original Array Elements");
61+
console.log(arr);
62+
console.log("Sorted Array Elements");
63+
console.log(combSort(arr));

0 commit comments

Comments
 (0)