Skip to content

Commit 600c20f

Browse files
authored
Create ComboSort
algo for combo sort
1 parent dff1b63 commit 600c20f

File tree

1 file changed

+52
-0
lines changed

1 file changed

+52
-0
lines changed

src/java/main/ComboSort.Java

Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
// Java program for implementation of Comb Sort
2+
class CombSort
3+
{
4+
// To find gap between elements
5+
int getNextGap(int gap)
6+
{
7+
// Shrink gap by Shrink factor
8+
gap = (gap*10)/13;
9+
if (gap < 1)
10+
return 1;
11+
return gap;
12+
}
13+
14+
// Function to sort arr[] using Comb Sort
15+
void sort(int arr[])
16+
{
17+
int n = arr.length;
18+
19+
// initialize gap
20+
int gap = n;
21+
22+
// Initialize swapped as true to make sure that
23+
// loop runs
24+
boolean swapped = true;
25+
26+
// Keep running while gap is more than 1 and last
27+
// iteration caused a swap
28+
while (gap != 1 || swapped == true)
29+
{
30+
// Find next gap
31+
gap = getNextGap(gap);
32+
33+
// Initialize swapped as false so that we can
34+
// check if swap happened or not
35+
swapped = false;
36+
37+
// Compare all elements with current gap
38+
for (int i=0; i<n-gap; i++)
39+
{
40+
if (arr[i] > arr[i+gap])
41+
{
42+
// Swap arr[i] and arr[i+gap]
43+
int temp = arr[i];
44+
arr[i] = arr[i+gap];
45+
arr[i+gap] = temp;
46+
47+
// Set swapped
48+
swapped = true;
49+
}
50+
}
51+
}
52+
}

0 commit comments

Comments
 (0)