forked from Coder-forfun/Hactoberfest-accepted
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathShell-Sort.c
50 lines (45 loc) · 1 KB
/
Shell-Sort.c
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
//This is the Shell Sort Program in C
#include<stdio.h>
#include<stdlib.h>
#include<time.h>
void print_array(int arr[], int n) {
for(int i=0;i<n;i++) {
printf("%d ",arr[i]);
}
}
void swap(int *x, int *y) {
int temp=(*x);
(*x)=(*y);
(*y)=temp;
}
void shell_sort(int arr[],int n) {
int gap, flag=1;
gap=n;
while(flag==1||gap>1) {
flag=0;
gap=(gap+1)/2;
for(int i=0;i<(n-gap);i++) {
if(arr[i+gap]<arr[i]) {
// printf("\nAt %d position, %d and %d is swapped!",i,arr[i+gap],arr[i]);
swap(&arr[i+gap],&arr[i]);
flag=0;
}
}
}
}
int main(void) {
srand(time(0));
int n;
printf("Enter the number of elements: ");
scanf("%d",&n);
int arr[n];
for(int i=0;i<n;i++) {
arr[i]=(rand()%1000);
}
printf("Array before sorting: \n");
print_array(arr,n);
shell_sort(arr,n);
printf("\nSorted array: \n");
print_array(arr,n);
return 0;
}