Skip to content
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
93 changes: 31 additions & 62 deletions sorting/shellSort.c
Original file line number Diff line number Diff line change
@@ -1,68 +1,37 @@
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include<stdio.h>

#define ELEMENT_NR 20
#define ARRAY_LEN(x) (sizeof(x) / sizeof((x)[0]))
const char *notation = "Shell Sort Big O Notation:\
\n--> Best Case: O(n log(n)) \
\n--> Average Case: depends on gap sequence \
\n--> Worst Case: O(n)";

void show_data(int arr[], int len)
{
int i;

for (i = 0; i < len; i++)
printf("%3d ", arr[i]);
printf("\n");
}

void swap(int *a, int *b)
void ShellSort(int a[], int n)
{
int tmp;

tmp = *a;
*a = *b;
*b = tmp;
int i, j, increment, tmp;
for(increment = n/2; increment > 0; increment /= 2)
{
for(i = increment; i < n; i++)
{
tmp = a[i];
for(j = i; j >= increment; j -= increment)
{
if(tmp < a[j-increment])
a[j] = a[j-increment];
else
break;
}
a[j] = tmp;
}
}
}

void shellSort(int array[], int len)
int main()
{
int i, j, gap;

for (gap = len / 2; gap > 0; gap = gap / 2)
for (i = gap; i < len; i++)
for (j = i - gap; j >= 0 && array[j] > array[j + gap]; j = j - gap)
swap(&array[j], &array[j + gap]);
}

int main(int argc, char *argv[])
{
int i;
int array[ELEMENT_NR];
int range = 500;
int size;
clock_t start, end;
double time_spent;

srand(time(NULL));
for (i = 0; i < ELEMENT_NR; i++)
array[i] = rand() % range + 1;

size = ARRAY_LEN(array);

show_data(array, size);
start = clock();
shellSort(array, size);
end = clock();
time_spent = (double)(end - start) / CLOCKS_PER_SEC;

printf("Data Sorted\n");
show_data(array, size);

printf("%s\n", notation);
printf("Time spent sorting: %f\n", time_spent);

int i, n, a[n];
scanf("%d",&n);
for(i = 0; i < n; i++)
{
scanf("%d",&a[i]);
}
ShellSort(a,n);
printf("The sorted elements are :: ");
for(i = 0; i < n; i++)
printf("%d ",a[i]);
printf("\n");
return 0;
}