forked from mayankchaudhary26/HacktoberFest-Practice-2021
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathShellSort.java
More file actions
53 lines (42 loc) Β· 1.24 KB
/
ShellSort.java
File metadata and controls
53 lines (42 loc) Β· 1.24 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
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
import java.util.Scanner;
public class ShellSort {
int shellsort(int arr[], int n) {
//here n is the size of the array
//initially gap = n/2
for (int gap = n / 2; gap > 0; gap = gap / 2) {
for (int i = gap; i < n; i++) {
//decreasing the gap
int k = arr[i];
int j = i;
while (j >= gap && arr[j - gap] > k) {
arr[j] = arr[j - gap];
j = j - gap;
}
arr[j] = k;
}
}
return 0;
}
private static Scanner sc = new Scanner(System.in);
public static void main(String args[]) {
//we store the number of elements in n
System.out.println("Kindly enter the number of elements: ");
int n = sc.nextInt();
//declaring an array of n elements
int array[] = new int[n];
//taking the input from the user
for (int i = 0; i < n; i++) {
System.out.print("\n" + i + "'th element : ");
array[i] = sc.nextInt();
}
System.out.println("\nArray before sorting");
for (int j = 0; j < n; j++)
System.out.print(array[j] + " ");
//creating an object of shellsort class so that the methods inside shellsort class can be used
ShellSort object = new ShellSort();
object.shellsort(array, n);
System.out.println("\nArray after sorting");
for (int k = 0; k < n; k++)
System.out.print(array[k] + " ");
}
}