mirror of https://github.com/TheAlgorithms/C
Modify insertionSort for more clear
This commit is contained in:
parent
5d7caa8328
commit
cd813030ea
|
@ -3,14 +3,11 @@
|
|||
|
||||
/*Displays the array, passed to this method*/
|
||||
void display(int arr[], int n) {
|
||||
|
||||
int i;
|
||||
for(i = 0; i < n; i++){
|
||||
printf("%d ", arr[i]);
|
||||
}
|
||||
|
||||
printf("\n");
|
||||
|
||||
}
|
||||
|
||||
/*This is where the sorting of the array takes place
|
||||
|
@ -18,13 +15,17 @@ void display(int arr[], int n){
|
|||
size --- Array Size
|
||||
*/
|
||||
void insertionSort(int arr[], int size) {
|
||||
int j,temp,i;
|
||||
int i, j, key;
|
||||
for(i = 0; i < size; i++) {
|
||||
temp = arr[(j=i)];
|
||||
while(--j >= 0 && temp < arr[j]) {
|
||||
j = i - 1;
|
||||
key = arr[i];
|
||||
/* Move all elements greater than key to one position */
|
||||
while(j >= 0 && key < arr[j]) {
|
||||
arr[j + 1] = arr[j];
|
||||
arr[j] = temp;
|
||||
j = j - 1;
|
||||
}
|
||||
/* Find a correct position for key */
|
||||
arr[j + 1] = key;
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -41,12 +42,12 @@ int main(int argc, const char * argv[]) {
|
|||
}
|
||||
|
||||
printf("Original array: ");
|
||||
display(arr, n); // Original array : 10 11 9 8 4 7 3 8
|
||||
display(arr, n);
|
||||
|
||||
insertionSort(arr, n);
|
||||
|
||||
printf("Sorted array: ");
|
||||
display(arr, n); // Sorted array : 3 4 7 8 8 9 10 11
|
||||
display(arr, n);
|
||||
|
||||
return 0;
|
||||
}
|
Loading…
Reference in New Issue