forked from mohitmishra786/hacktoberfest-2022
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathshellSort.java
42 lines (35 loc) · 1023 Bytes
/
shellSort.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
## Shell sort
import java.util.*;
class ShellSort{
public static void main(String[]args){
Scanner sc = new Scanner(System.in);
System.out.println("Enter the size of an array: ");
int n = sc.nextInt();
// Taking input elements in array
int []arr = new int[n];
System.out.println("Enter "+n+" element: ");
for(int i=0; i<n; i++) {
arr[i] = sc.nextInt();
}
shellSort(arr);
// Printing the elements of the array
for (int j : arr) {
System.out.print(j + ", ");
}
}
public static void shellSort(int arr[]) {
int n = arr.length;
// Start with a big gap, then reduce the gap
for (int gap = n / 2; gap > 0; gap /= 2) {
for (int i = gap; i < n; i++) {
int temp = arr[i];
int j = i;
while (j >= gap && arr[j-gap] > temp) {
arr[j] = arr[j-gap];
j -= gap;
}
arr[j] = temp;
}
}
}
}