Modify insertionSort for more clear

This commit is contained in:
dang hai 2019-07-25 16:10:19 -07:00
parent 5d7caa8328
commit cd813030ea
1 changed files with 20 additions and 19 deletions

View File

@ -2,29 +2,30 @@
#include <stdio.h>
/*Displays the array, passed to this method*/
void display(int arr[], int n){
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
arr[] --- Array to be sorted
size --- Array Size
*/
void insertionSort(int arr[], int size){
int j,temp,i;
for(i=0; i<size; i++) {
temp = arr[(j=i)];
while(--j >= 0 && temp < arr[j]) {
arr[j+1] = arr[j];
arr[j] = temp;
void insertionSort(int arr[], int size) {
int i, j, key;
for(i = 0; i < size; i++) {
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];
j = j - 1;
}
/* Find a correct position for key */
arr[j + 1] = key;
}
}
@ -32,22 +33,22 @@ int main(int argc, const char * argv[]) {
int n;
printf("Enter size of array:\n");
scanf("%d", &n); // E.g. 8
printf("Enter the elements of the array\n");
int i;
int arr[n];
for(i = 0; i < n; i++){
for(i = 0; i < n; i++) {
scanf("%d", &arr[i] );
}
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;
}