Skip to content

Commit 120947a

Browse files
authored
Merge pull request TheAlgorithms#65 from KuLi/combSort
Implemented comb sort algorithm
2 parents 988572e + 3afb902 commit 120947a

File tree

1 file changed

+53
-0
lines changed

1 file changed

+53
-0
lines changed

Sorts/combSort.js

Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
1+
/*
2+
Wikipedia says: Comb sort improves on bubble sort.
3+
4+
The basic idea is to eliminate turtles, or small values
5+
near the end of the list, since in a bubble sort these slow the sorting
6+
down tremendously. Rabbits, large values around the beginning of the list,
7+
do not pose a problem in bubble sort.
8+
9+
In bubble sort, when any two elements are compared, they always have a
10+
gap (distance from each other) of 1. The basic idea of comb sort is
11+
that the gap can be much more than 1. The inner loop of bubble sort,
12+
which does the actual swap, is modified such that gap between swapped
13+
elements goes down (for each iteration of outer loop) in steps of
14+
a "shrink factor" k: [ n/k, n/k2, n/k3, ..., 1 ].
15+
16+
*/
17+
function combSort(list) {
18+
19+
20+
if (list.length === 0) {
21+
return list;
22+
}
23+
let shrink = 1.3;
24+
let gap = list.length;
25+
let isSwapped = true;
26+
let i = 0
27+
28+
while (gap > 1 || isSwapped) {
29+
// Update the gap value for a next comb
30+
gap = parseInt(parseFloat(gap) / shrink, 10);
31+
32+
isSwapped = false
33+
i = 0
34+
35+
while (gap + i < list.length) {
36+
if (list[i] > list[i + gap]) {
37+
38+
let value = list[i];
39+
list[i] = list[i + gap];
40+
list[i + gap] = value;
41+
isSwapped = true;
42+
}
43+
i += 1
44+
}
45+
}
46+
return list
47+
}
48+
let arrOrignal = [5, 6, 7, 8, 1, 2, 12, 14];
49+
//Array before Sort
50+
console.log(arrOrignal);
51+
arrSorted = combSort(arrOrignal);
52+
//Array after sort
53+
console.log(arrSorted);

0 commit comments

Comments
 (0)
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy