Skip to content

Commit f9b6419

Browse files
Implemented Comb Sort in Java
1 parent bdaaa5b commit f9b6419

File tree

1 file changed

+66
-0
lines changed

1 file changed

+66
-0
lines changed

Diff for: sortingAlgo/combSort/combSort.java

+66
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,66 @@
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+
}
53+
54+
// Driver method
55+
public static void main(String args[])
56+
{
57+
CombSort ob = new CombSort();
58+
int arr[] = {8, 4, 1, 56, 3, -44, 23, -6, 28, 0};
59+
ob.sort(arr);
60+
61+
System.out.println("sorted array");
62+
for (int i=0; i<arr.length; ++i)
63+
System.out.print(arr[i] + " ");
64+
65+
}
66+
}

0 commit comments

Comments
 (0)