TheAlgorithms-C/sorting/insertionSort.c

55 lines
1.1 KiB
C
Raw Normal View History

2018-11-13 07:42:00 +03:00
//sorting of array list using insertion sort
2017-03-23 17:15:17 +03:00
#include <stdio.h>
2018-11-08 10:37:38 +03:00
/*Displays the array, passed to this method*/
2019-07-26 02:10:19 +03:00
void display(int arr[], int n) {
2018-11-08 10:37:38 +03:00
int i;
for(i = 0; i < n; i++){
printf("%d ", arr[i]);
}
printf("\n");
}
2017-10-17 23:32:52 +03:00
2018-11-08 10:37:38 +03:00
/*This is where the sorting of the array takes place
arr[] --- Array to be sorted
size --- Array Size
*/
2019-07-26 02:10:19 +03:00
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;
2017-03-23 17:15:17 +03:00
}
2019-07-26 02:10:19 +03:00
/* Find a correct position for key */
arr[j + 1] = key;
2018-11-08 10:37:38 +03:00
}
}
2017-03-23 17:15:17 +03:00
2018-11-08 10:37:38 +03:00
int main(int argc, const char * argv[]) {
int n;
printf("Enter size of array:\n");
scanf("%d", &n); // E.g. 8
2019-07-26 02:10:19 +03:00
2018-11-08 10:37:38 +03:00
printf("Enter the elements of the array\n");
int i;
int arr[n];
2019-07-26 02:10:19 +03:00
for(i = 0; i < n; i++) {
2018-11-08 10:37:38 +03:00
scanf("%d", &arr[i] );
}
2019-07-26 02:10:19 +03:00
2018-11-08 10:37:38 +03:00
printf("Original array: ");
2019-07-26 02:10:19 +03:00
display(arr, n);
2018-11-08 10:37:38 +03:00
insertionSort(arr, n);
2019-07-26 02:10:19 +03:00
2018-11-08 10:37:38 +03:00
printf("Sorted array: ");
2019-07-26 02:10:19 +03:00
display(arr, n);
2018-11-08 10:37:38 +03:00
return 0;
2017-03-23 17:15:17 +03:00
}
2018-11-08 10:37:38 +03:00