Skip to content

Commit 7acb30a

Browse files
yashaglditabranhe
authored andcommitted
Added ShellSort
1 parent 5cddf10 commit 7acb30a

File tree

1 file changed

+58
-0
lines changed

1 file changed

+58
-0
lines changed

sorting/ShellSort.java

Lines changed: 58 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,58 @@
1+
class ShellSort
2+
{
3+
/* An utility function to print array of size n*/
4+
static void printArray(int arr[])
5+
{
6+
int n = arr.length;
7+
for (int i=0; i<n; ++i)
8+
System.out.print(arr[i] + " ");
9+
System.out.println();
10+
}
11+
12+
/* function to sort arr using shellSort */
13+
int sort(int arr[])
14+
{
15+
int n = arr.length;
16+
17+
// Start with a big gap, then reduce the gap
18+
for (int gap = n/2; gap > 0; gap /= 2)
19+
{
20+
// Do a gapped insertion sort for this gap size.
21+
// The first gap elements a[0..gap-1] are already
22+
// in gapped order keep adding one more element
23+
// until the entire array is gap sorted
24+
for (int i = gap; i < n; i += 1)
25+
{
26+
// add a[i] to the elements that have been gap
27+
// sorted save a[i] in temp and make a hole at
28+
// position i
29+
int temp = arr[i];
30+
31+
// shift earlier gap-sorted elements up until
32+
// the correct location for a[i] is found
33+
int j;
34+
for (j = i; j >= gap && arr[j - gap] > temp; j -= gap)
35+
arr[j] = arr[j - gap];
36+
37+
// put temp (the original a[i]) in its correct
38+
// location
39+
arr[j] = temp;
40+
}
41+
}
42+
return 0;
43+
}
44+
45+
// Driver method
46+
public static void main(String args[])
47+
{
48+
int arr[] = {12, 34, 54, 2, 3};
49+
System.out.println("Array before sorting");
50+
printArray(arr);
51+
52+
ShellSort ob = new ShellSort();
53+
ob.sort(arr);
54+
55+
System.out.println("Array after sorting");
56+
printArray(arr);
57+
}
58+
}

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