Skip to content

Commit 1f76cda

Browse files
author
Christian Bender
authored
Merge pull request TheAlgorithms#287 from sandeeproy99/patch-3
CombSort.java
2 parents 8dcc57f + f8542e4 commit 1f76cda

1 file changed

Lines changed: 62 additions & 0 deletions

File tree

Sorts/CombSort.java

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

0 commit comments

Comments
 (0)