Created
January 12, 2014 09:41
-
-
Save beginor/8382698 to your computer and use it in GitHub Desktop.
insertion sort demo in c
This file contains hidden or 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> | |
#include <stdlib.h> | |
void insertion_sort(int arr[], const int N); | |
void swap(int arr[], int i, int j); | |
void printArray(int array[]); | |
int main(int argc, char *argv[]) { | |
int array[] = { 10, 19, 13, 16, 20, 32, 27, 22, 15, 18, 21 }; | |
printArray(array); | |
insertion_sort(array, sizeof(array) / sizeof(array[0])); | |
printArray(array); | |
return 0; | |
} | |
void insertion_sort(int arr[], const int N) { | |
for (int i = 1; i < N; i++) { | |
for (int j = i; j > 0 && arr[j] > arr[j - 1]; j--) { | |
swap(arr, j, j - 1); | |
} | |
} | |
} | |
void swap(int arr[], int i, int j) { | |
int tmp = arr[i]; | |
arr[i] = arr[j]; | |
arr[j] = tmp; | |
} | |
void printArray(int array[]) { | |
int i = 0; | |
while (array[i] > 0) { | |
printf("%d ", array[i]); | |
i++; | |
} | |
printf("\n"); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment