Skip to content

Commit

Permalink
Modify insertionSort for more clear
Browse files Browse the repository at this point in the history
  • Loading branch information
danghai committed Jul 25, 2019
1 parent 5d7caa8 commit cd81303
Showing 1 changed file with 20 additions and 19 deletions.
39 changes: 20 additions & 19 deletions sorting/InsertionSort.c → sorting/insertionSort.c
Original file line number Diff line number Diff line change
Expand Up @@ -2,52 +2,53 @@
#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;
}
}

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;
}

0 comments on commit cd81303

Please sign in to comment.