-
-
Save myusufid/0b0fced95d76e166164547cdbc3a9a53 to your computer and use it in GitHub Desktop.
Insertion Sort in C++
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 <cstdio> | |
#include <cstdlib> | |
void insertionSort(int arr[], int length) { | |
int i, j, tmp; | |
for (i = 1; i < length; i++) { | |
j = i; | |
while (j > 0 && arr[j - 1] > arr[j]) { | |
tmp = arr[j]; | |
arr[j] = arr[j - 1]; | |
arr[j - 1] = tmp; | |
j--; | |
} | |
} | |
} | |
int displayArray( int arr[], int length ) { | |
printf("{"); | |
for( int i=0; i<length; i++ ) | |
printf("%d, ", arr[i] ); | |
printf("}\n"); | |
} | |
int main( int argc, char* argv[] ) | |
{ | |
int array[10] = { 2,1,7,4,3,5,9,6,8,0 }; | |
size_t length = sizeof(array)/sizeof(int); | |
displayArray( array, length ); | |
insertionSort( array, length ); | |
displayArray( array, length ); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment