Created
October 12, 2015 08:00
-
-
Save joequery/8e33be3f5e9d58cc0546 to your computer and use it in GitHub Desktop.
Recursive C Insertion Sort
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include<stdio.h> | |
#define ARR_SIZE 6 | |
void print_r(int *arr, size_t n); | |
void insertion_sort(int *arr, size_t n, size_t i); | |
int main(){ | |
int nums[ARR_SIZE] = {2,8,9,0,0,2}; | |
print_r(nums, ARR_SIZE); | |
printf("Sorting...\n"); | |
insertion_sort(nums, ARR_SIZE, 0); | |
print_r(nums, ARR_SIZE); | |
return 0; | |
} | |
void print_r(int *arr, size_t n){ | |
int i; | |
printf("Array\n(\n"); | |
for(i=0; i<n; i++){ | |
printf("\t[%d] => %d\n", i, arr[i]); | |
} | |
printf(")\n"); | |
} | |
/* | |
* This insertion sort will be done in place as opposed to the PHP | |
* implementation. | |
*/ | |
void insertion_sort(int *arr, size_t n, size_t i){ | |
int el,j; | |
if(i == n-1){ | |
// Nothing to do since we're looking at the last element. | |
} | |
else{ | |
insertion_sort(arr, n, i+1); | |
el = arr[i]; | |
// All elements to the right of index i are assumed to be sorted. | |
// Now we just have to figure out where el fits in the sorted array | |
for(j = i+1; j<n; j++){ | |
if(el > arr[j]){ | |
// el is bigger, swap so el moves to the right in the array. | |
arr[j-1] = arr[j]; | |
arr[j] = el; | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment