-
Notifications
You must be signed in to change notification settings - Fork 21
/
Copy pathshell_sort.java
45 lines (36 loc) · 1.18 KB
/
shell_sort.java
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
37
38
39
40
41
42
43
44
45
import java.util.Scanner;
public class shell_sort {
public static void shellSort(int[] arr) {
int n = arr.length;
for (int gap = n / 2; gap > 0; gap /= 2) {
for (int i = gap; i < n; i++) {
int temp = arr[i];
int j;
for (j = i; j >= gap && arr[j - gap] > temp; j -= gap) {
arr[j] = arr[j - gap];
}
arr[j] = temp;
}
}
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the number of elements: ");
int n = scanner.nextInt();
int[] arr = new int[n];
System.out.println("Enter " + n + " elements:");
for (int i = 0; i < n; i++) {
arr[i] = scanner.nextInt();
}
scanner.close();
System.out.println("Original array: ");
for (int num : arr) {
System.out.print(num + " ");
}
shellSort(arr);
System.out.println("\nSorted array: ");
for (int num : arr) {
System.out.print(num + " ");
}
}
}