forked from DhanushNehru/Hacktoberfest2025
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathshellsort.java
More file actions
36 lines (33 loc) · 1.16 KB
/
shellsort.java
File metadata and controls
36 lines (33 loc) · 1.16 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
public class ShellSort {
public static void main(String[] args) {
// An array of integers
int[] a = {23, 29, 15, 19, 31, 7, 9, 5, 2};
int nElements = a.length;
// Printing unsorted array
System.out.println("Unsorted array:");
for (int i = 0; i < nElements; i++) {
System.out.print(a[i] + "\t");
}
System.out.println();
// SHELL sort
for (int gap = nElements / 2; gap >= 1; gap /= 2) { // Loop for gap
for (int j = gap; j < nElements; j++) { // For passes
for (int i = j - gap; i >= 0; i -= gap) { // Comparisons within each pass
if (a[i + gap] > a[i]) {
break;
} else {
// Swap a[i+gap] with a[i]
int temp = a[i + gap];
a[i + gap] = a[i];
a[i] = temp;
}
}
}
}
// Printing sorted array
System.out.println("\nSorted array:");
for (int i = 0; i < nElements; i++) {
System.out.print(a[i] + "\t");
}
}
}