Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commitc6887b8

Browse files
Merge pull requestTheAlgorithms#100 from dpunosevac/master
Added Shell Sort
2 parents230a005 +f7f70b5 commitc6887b8

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+
packageSorts;
2+
3+
/**
4+
* @author dpunosevac
5+
*/
6+
publicclassShellSort {
7+
8+
/**
9+
* This method implements Generic Shell Sort.
10+
* @param array The array to be sorted
11+
*/
12+
publicstaticvoidshellSort(Comparable[]array) {
13+
intN =array.length;
14+
inth =1;
15+
16+
while (h <N/3) {
17+
h =3 *h +1;
18+
}
19+
20+
while (h >=1) {
21+
for (inti =h;i <N;i++) {
22+
for (intj =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+
privatestaticvoidexch(Comparable[]array,inti,intj) {
38+
Comparableswap =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+
privatestaticbooleanless(Comparablev,Comparablew) {
50+
returnv.compareTo(w) <0;
51+
}
52+
53+
publicstaticvoidmain(String[]args) {
54+
// Integer Input
55+
int[]arr1 = {4,23,6,78,1,54,231,9,12};
56+
Integer[]array =newInteger[arr1.length];
57+
58+
for (inti=0;i<arr1.length;i++) {
59+
array[i] =arr1[i];
60+
}
61+
62+
shellSort(array);
63+
64+
for (inti =0;i <array.length;i++) {
65+
System.out.println(array[i]);
66+
}
67+
}
68+
}

0 commit comments

Comments
 (0)

[8]ページ先頭

©2009-2025 Movatter.jp