Skip to content

Commit 74995b0

Browse files
authored
Merge pull request tulika-99#64 from Ashraf-101/master
Added shell sort Java version
2 parents 011f829 + 290f03e commit 74995b0

File tree

2 files changed

+59
-0
lines changed

2 files changed

+59
-0
lines changed

Shell sort/explaination.txt

+1
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
ShellSort is mainly a variation of Insertion Sort. In insertion sort, we move elements only one position ahead. When an element has to be moved far ahead, many movements are involved. The idea of shellSort is to allow exchange of far items. In shellSort, we make the array h-sorted for a large value of h. We keep reducing the value of h until it becomes 1. An array is said to be h-sorted if all sublists of every h’th element is sorted.

Shell sort/shellsort-java.txt

+58
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,58 @@
1+
class ShellSort
2+
{
3+
/* An 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)