From c6bc541ab58363d783e60a007e80e9bf9e231fda Mon Sep 17 00:00:00 2001 From: garhve Date: Mon, 5 Dec 2022 19:43:39 +0800 Subject: initialize --- c/dataStructure/sorting/insertSort.c | 60 ++++++++++++++++++++++++++++++++++++ 1 file changed, 60 insertions(+) create mode 100755 c/dataStructure/sorting/insertSort.c (limited to 'c/dataStructure/sorting/insertSort.c') diff --git a/c/dataStructure/sorting/insertSort.c b/c/dataStructure/sorting/insertSort.c new file mode 100755 index 0000000..741f295 --- /dev/null +++ b/c/dataStructure/sorting/insertSort.c @@ -0,0 +1,60 @@ +#include +#include +#include + +#define SIZE 10 + +void swap(int * a, int * b) +{ + int tmp = *a; + *a = *b; + *b = tmp; +} + +void generateRandom(int * arr, int n) +{ + time_t sr; + srand(*&sr); + + for(int i = 0; i < n; i++) + arr[i] = rand() % 100; +} + +void print(int * arr, int n) +{ + for(int i = 0; i < n; i++) + printf("%3d",*(arr+i)); + putchar('\n'); +} + +void insertSort(int * arr, int n) +{ + int key, i, j; + + for (i = 1; i < n; i++) + { + key = arr[i]; + j = i - 1; + + while (j >= 0 && key < arr[j]) + { + arr[j+1] = arr[j]; + j--; + } + arr[j+1] = key; + } +} + +int main(void) +{ + int arr[SIZE]; + generateRandom(arr,SIZE); + + print(arr,SIZE); + + insertSort(arr,SIZE); + + print(arr,SIZE); + + return 0; +} -- cgit v1.2.3-70-g09d2