Skip to content

Commit c6887b8

Browse files
Merge pull request TheAlgorithms#100 from dpunosevac/master
Added Shell Sort
2 parents 230a005 + f7f70b5 commit c6887b8

File tree

1 file changed

+68
-0
lines changed

1 file changed

+68
-0
lines changed

Sorts/ShellSort.java

Lines changed: 68 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,68 @@
1+
package Sorts;
2+
3+
/**
4+
* @author dpunosevac
5+
*/
6+
public class ShellSort {
7+
8+
/**
9+
* This method implements Generic Shell Sort.
10+
* @param array The array to be sorted
11+
*/
12+
public static void shellSort(Comparable[] array) {
13+
int N = array.length;
14+
int h = 1;
15+
16+
while (h < N/3) {
17+
h = 3 * h + 1;
18+
}
19+
20+
while (h >= 1) {
21+
for (int i = h; i < N; i++) {
22+
for (int j = i; j >= h && less(array[j], array[j-h]); j -= h) {
23+
exch(array, j, j - h);
24+
}
25+
}
26+
27+
h /= 3;
28+
}
29+
}
30+
31+
/**
32+
* Helper method for exchanging places in array
33+
* @param array The array which elements we want to swap
34+
* @param i index of the first element
35+
* @param j index of the second element
36+
*/
37+
private static void exch(Comparable[] array, int i, int j) {
38+
Comparable swap = array[i];
39+
array[i] = array[j];
40+
array[j] = swap;
41+
}
42+
43+
/**
44+
* This method checks if first element is less then the other element
45+
* @param v first element
46+
* @param w second element
47+
* @return true if the first element is less then the second element
48+
*/
49+
private static boolean less(Comparable v, Comparable w) {
50+
return v.compareTo(w) < 0;
51+
}
52+
53+
public static void main(String[] args) {
54+
// Integer Input
55+
int[] arr1 = {4,23,6,78,1,54,231,9,12};
56+
Integer[] array = new Integer[arr1.length];
57+
58+
for (int i=0;i<arr1.length;i++) {
59+
array[i] = arr1[i];
60+
}
61+
62+
shellSort(array);
63+
64+
for (int i = 0; i < array.length; i++) {
65+
System.out.println(array[i]);
66+
}
67+
}
68+
}

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