TheAlgorithms-C/sorting/insertion_sort.c

63 lines
1.2 KiB
C
Raw Normal View History

// sorting of array list using insertion sort
2017-03-23 17:15:17 +03:00
#include <stdio.h>
#include <stdlib.h>
2017-03-23 17:15:17 +03:00
2018-11-08 10:37:38 +03:00
/*Displays the array, passed to this method*/
void display(int *arr, int n)
{
2018-11-08 10:37:38 +03:00
int i;
for (i = 0; i < n; i++)
{
2018-11-08 10:37:38 +03:00
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
*/
void insertionSort(int *arr, int size)
{
2019-07-26 02:10:19 +03:00
int i, j, key;
for (i = 0; i < size; i++)
{
2019-07-26 02:10:19 +03:00
j = i - 1;
key = arr[i];
/* Move all elements greater than key to one position */
while (j >= 0 && key < arr[j])
{
2019-07-26 02:10:19 +03:00
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
int main(int argc, const char *argv[])
{
2018-11-08 10:37:38 +03:00
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 = (int *)malloc(n * sizeof(int));
for (i = 0; i < n; i++)
{
scanf("%d", &arr[i]);
2018-11-08 10:37:38 +03:00
}
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);
free(arr);
2018-11-08 10:37:38 +03:00
return 0;
2017-03-23 17:15:17 +03:00
}