Insertion sort is a simple sorting algorithm that works by iterating through the elements of an array and inserting them into the correct position in a sorted array. It is an efficient algorithm for sorting small arrays, but it is not as efficient for larger arrays.
Here is an example of how to implement insertion sort in C:
#include <stdio.h>
// function to sort an array using insertion sort
void insertion_sort(int array[], int size) {
int i, j, key;
// iterate through the array
for (i = 1; i < size; i++) {
key = array[i]; // store the current element
j = i - 1; // initialize the counter
// find the correct position for the current element
while (j >= 0 && array[j] > key) {
array[j+1] = array[j]; // shift the element to the right
j = j - 1; // move to the next element
}
// insert the element at the correct position
array[j+1] = key;
}
}
// main function
int main() {
int array[] = {5, 2, 4, 1, 3}; // declare and initialize an array to sort
int size = sizeof(array) / sizeof(array[0]); // calculate the size of the array
printf("Original array: ");
for (int i = 0; i < size; i++) {
printf("%d ", array[i]); // print the original array
}
printf("\n");
insertion_sort(array, size); // sort the array using insertion sort
printf("Sorted array: ");
for (int i = 0; i < size; i++) {
printf("%d ", array[i]); // print the sorted array
}
printf("\n");
return 0;
}
In this example, the function “insertion_sort” takes an array and its size as arguments, and sorts the array using insertion sort. The function iterates through the elements of the array, and inserts them into the correct position in a sorted array using a loop. The main function declares and initializes an array to sort, and calls the “insertion_sort” function to sort the array. The sorted array is then printed to the console.
The output of the program will be:
Original array: 5 2 4 1 3
Sorted array: 1 2 3 4 5
This is an example of how to implement insertion sort in C. You can modify the function to suit your needs, such as sorting in descending order or using a different data type for the elements of the array.