TheAlgorithms-C/sorting/shellSort.c

69 lines
1.4 KiB
C
Raw Normal View History

2017-09-28 23:31:27 +03:00
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define ELEMENT_NR 20
2019-05-05 10:34:27 +03:00
#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)
{
2019-05-05 10:34:27 +03:00
int i;
2019-05-05 10:34:27 +03:00
for (i = 0; i < len; i++)
printf("%3d ", arr[i]);
printf("\n");
2017-09-28 23:31:27 +03:00
}
void swap(int *a, int *b)
{
2019-05-05 10:34:27 +03:00
int tmp;
2017-09-28 23:31:27 +03:00
2019-05-05 10:34:27 +03:00
tmp = *a;
*a = *b;
*b = tmp;
}
2017-09-28 23:31:27 +03:00
void shellSort(int array[], int len)
{
2019-05-05 10:34:27 +03:00
int i, j, gap;
2017-09-28 23:31:27 +03:00
2019-05-05 10:34:27 +03:00
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]);
}
2017-09-28 23:31:27 +03:00
int main(int argc, char *argv[])
{
2019-05-05 10:34:27 +03:00
int i;
int array[ELEMENT_NR];
int range = 500;
int size;
clock_t start, end;
double time_spent;
2017-09-28 23:31:27 +03:00
2019-05-05 10:34:27 +03:00
srand(time(NULL));
for (i = 0; i < ELEMENT_NR; i++)
array[i] = rand() % range + 1;
2017-09-28 23:31:27 +03:00
2019-05-05 10:34:27 +03:00
size = ARRAY_LEN(array);
2017-09-28 23:31:27 +03:00
2019-05-05 10:34:27 +03:00
show_data(array, size);
start = clock();
shellSort(array, size);
end = clock();
time_spent = (double)(end - start) / CLOCKS_PER_SEC;
2017-09-28 23:31:27 +03:00
2019-05-05 10:34:27 +03:00
printf("Data Sorted\n");
show_data(array, size);
2019-05-05 10:34:27 +03:00
printf("%s\n", notation);
printf("Time spent sorting: %f\n", time_spent);
2017-09-28 23:31:27 +03:00
2019-05-05 10:34:27 +03:00
return 0;
}