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

Commit

Permalink
Add Comb Sort Algorithm in Javascript/Algorithms (#939)
Browse files Browse the repository at this point in the history
  • Loading branch information
bhaveshmhadse authored Jul 6, 2023
1 parent 560565a commit 7d7b56c
Showing 1 changed file with 63 additions and 0 deletions.
63 changes: 63 additions & 0 deletions Javascript/Algorithms/comb-sort.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
/**
* Time Complexity:
* O(n^2), where n is the length of the input array.
* Space Complexity:
* O(1), as sorting happens in-place in comb-sort.
**/

/**
* @param {number[]}
* @return {number[]}
*/
const combSort = arr => {
/**
* @param {number[]}
* @return {boolean}
*/
const isArraySorted = arr => {
for (let i = 0; i < arr.length - 1; i++) {
if (arr[i] > arr[i + 1]) return false;
}
return true;
};

let iterationCount = 0;
let gap = arr.length - 2;
let decreaseFactor = 1.25;

// Repeat iterations Until array is not sorted

while (!isArraySorted(arr)) {
// If not first gap Calculate gap
if (iterationCount > 0) {
if (gap != 1) {
gap = Math.floor(gap / decreaseFactor);
}
}
// Set front and back elements and increment to a gap
let front = 0;
let back = gap;
while (back <= arr.length - 1) {
// Swap the elements if they are not ordered
if (arr[front] > arr[back]) {
let temp = arr[front];
arr[front] = arr[back];
arr[back] = temp;
}

// Increment and re-run swapping
front += 1;
back += 1;
}
iterationCount += 1;
}
return arr;
};

let arr = [3, 0, 2, 5, -1, -2, -1, 4, 1];

console.log("Original Array Elements");
console.log(arr);
console.log("Sorted Array Elements");
console.log(combSort(arr));

0 comments on commit 7d7b56c

Please sign in to comment.