Created
April 1, 2019 12:10
-
-
Save jatinsharrma/f56b04bd069a6e5e7f365b8093d1a3dc to your computer and use it in GitHub Desktop.
Sorting an array - Insertion Sort
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> | |
| int swap(int* i, int* j){ | |
| int temp = *i; | |
| *i = *j; | |
| *j = temp; | |
| } | |
| int InsertionSort(int array[], int size){ | |
| for (int i =1 ; i < size ; i++){ | |
| int temp = i; | |
| int j = i-1; | |
| while(j>=0 && array[j]>array[i]){ | |
| swap(&array[j+1],&array[j]); | |
| j = j-1; | |
| i = i-1; | |
| } | |
| i = temp; | |
| //Uncomment this to see changes after every loop | |
| //for (int k = 0 ; k<size; k++){ | |
| // printf("%d ", array[k]); | |
| //} | |
| //printf("\n"); | |
| } | |
| } | |
| void print(int array[], int size){ | |
| for (int i = 0 ; i<size ; i++){ | |
| printf("%d\n",array[i]); | |
| } | |
| } | |
| void main() { | |
| int array[] = {9,8,7,6,5,4,3,2,1,0}; | |
| int size = sizeof(array)/sizeof(array[0]); | |
| InsertionSort(array,size); | |
| print(array,size); | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment