Skip to content

Commit a223278

Browse files
Shell Sort in java
1 parent c466aad commit a223278

File tree

1 file changed

+33
-0
lines changed

1 file changed

+33
-0
lines changed

MyClass.java

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
/*Shell sort addresses this problem and reduces the number of shifts/swaps by dividing the array into subarrays of intervals (gap) and then applying insertion sort on
2+
the sub-arrays. This process is repeated with reducing interval (gap) size until the gap becomes 0.
3+
As a result, the number of swaps significantly reduces but at the cost of more number of comparisons.*/
4+
5+
6+
public class MyClass {
7+
public static void main(String args[]) {
8+
int arr[] = {4,2,8,4,6,1};
9+
shellSort(arr);
10+
for(int i=0;i<arr.length;i++)
11+
System.out.print(arr[i]+" ");
12+
}
13+
public static void shellSort(int arr[])
14+
{
15+
int n = arr.length;
16+
int gap = n/2;
17+
while(gap>0)
18+
{
19+
for(int i=gap;i<n;i++)
20+
{
21+
int temp = arr[i];
22+
int j=i;
23+
while(j>=gap && arr[j-gap]>temp)
24+
{
25+
arr[j] = arr[j-gap];
26+
j -= gap;
27+
}
28+
arr[j] = temp;
29+
}
30+
gap = gap/2;
31+
}
32+
}
33+
}

0 commit comments

Comments
 (0)