Sort an array using insertion sort using the C programming language

Sort an array using insertion sort using the C programming language
Posted on 29-08-2023

Sort an array using insertion sort using the C programming language

Code:

#include <stdio.h>

void insertionSort(int arr[], int size) {
for (int i = 1; i < size; i++) {
int key = arr[i];
int j = i - 1;

// Move elements of arr[0..i-1], that are greater than key,
// to one position ahead of their current position
while (j >= 0 && arr[j] > key) {
arr[j + 1] = arr[j];
j--;
}
arr[j + 1] = key;
}
}

void printArray(int arr[], int size) {
for (int i = 0; i < size; i++) {
printf("%d ", arr[i]);
}
printf("\n");
}

int main() {
int arr[] = {12, 11, 13, 5, 6};
int size = sizeof(arr) / sizeof(arr[0]);

printf("Original array: ");
printArray(arr, size);

insertionSort(arr, size);

printf("Sorted array: ");
printArray(arr, size);

return 0;
}

Copy and paste this code into a C compiler, and it should sort the array using the insertion sort algorithm. The insertionSort function takes an array and its size as arguments and sorts the array in ascending order. The printArray function is used to print the contents of an array. The main function demonstrates the usage of the sorting function on a sample array.

 

Explanation:

#include <stdio.h>

This line includes the standard input-output library which provides functions like printf and scanf for input and output operations.

void insertionSort(int arr[], int size) {

This line starts the definition of the insertionSort function. It takes two arguments: an integer array arr and an integer size representing the size of the array.

for (int i = 1; i < size; i++) {

This line starts a for loop that iterates over each element of the array, starting from index 1 (because the element at index 0 is considered already sorted).

int key = arr[i];
int j = i - 1;

Here, we declare two variables: key to store the current element being considered for insertion, and j to keep track of the index before the current element.

while (j >= 0 && arr[j] > key) {

This line starts a while loop that continues as long as j is greater than or equal to 0 and the element at index j is greater than the key. This loop is used to find the correct position for the key in the sorted part of the array.

arr[j + 1] = arr[j];
j--;

Within the while loop, these lines shift elements that are greater than the key to the right by one position. This makes space for the key to be inserted in the correct position.

arr[j + 1] = key;

Once the correct position is found, this line assigns the value of key to the newly opened position, effectively inserting it into the correct place in the sorted part of the array.

}
}

This closes the for loop and completes the insertionSort function.

void printArray(int arr[], int size) {

This line starts the definition of the printArray function, which takes an integer array arr and an integer size as arguments.

for (int i = 0; i < size; i++) {

This line starts a for loop that iterates over each element of the array.

printf("%d ", arr[i]);

Within the loop, this line uses the printf function to print each element of the array followed by a space.

}
printf("\n");
}

This completes the printArray function. After the loop, a newline character is printed to move to the next line after printing the array.

int main() {

This is the beginning of the main function, the entry point of the program.

int arr[] = {12, 11, 13, 5, 6};

Here, we initialize an integer array arr with some sample values.

int size = sizeof(arr) / sizeof(arr[0]);

This line calculates the size of the array by dividing the total size of the array by the size of a single element.

printf("Original array: ");
printArray(arr, size);

These lines print the original array using the printArray function.

insertionSort(arr, size);

This line calls the insertionSort function to sort the array in place.

printf("Sorted array: ");
printArray(arr, size);

Finally, these lines print the sorted array using the printArray function.

return 0;
}
The main function is closed, and return 0; indicates successful execution of the program. This value is returned to the operating system.
 

Algorithm:

Insertion Sort Algorithm:

  1. Start with the second element (index 1) of the array. The first element (index 0) is assumed to be sorted.

  2. Store the current element in a variable called key.

  3. Initialize a variable j with the value of the index before the current element (i.e., j = i - 1).

  4. Compare the key with the element at index j.

  5. While j is greater than or equal to 0 and the element at index j is greater than the key, do the following:

    • Shift the element at index j to the right by one position (i.e., arr[j + 1] = arr[j]).

    • Decrement j by 1 to move to the previous element.

  6. Once the correct position for the key is found (i.e., either j becomes less than 0 or the element at index j is not greater than the key), insert the key at index j + 1.

  7. Repeat steps 2 to 6 for all elements of the array.

  8. The array is now sorted in ascending order.

This algorithm essentially builds the sorted part of the array by inserting elements from the unsorted part into their correct positions in the sorted part.

 

Time Complexity:

The time complexity of the above program, which implements the insertion sort algorithm, is O(n^2).

The insertion sort algorithm involves two nested loops:

  1. The outer loop runs for n-1 iterations (where n is the number of elements in the array). This loop iterates through each element of the array except the first one.

  2. The inner loop, nested inside the outer loop, runs for a variable number of iterations depending on the current position of the outer loop. In the worst case, the inner loop might need to iterate through almost all previous elements before finding the correct position for the current element.

In the worst case scenario, where the array is in reverse order, the inner loop would perform roughly (n-1) + (n-2) + ... + 2 + 1 iterations, which is the sum of the first n-1 natural numbers. This sum is approximately n^2 / 2, leading to a quadratic time complexity of O(n^2).

The best case scenario occurs when the array is already sorted. In this case, the inner loop might not need to perform any iterations, but the outer loop will still run for n-1 iterations. This leads to a linear time complexity of O(n) in the best case.

On average, the insertion sort algorithm has a quadratic time complexity due to its comparison and shifting operations for each element in the array. While insertion sort is not the most efficient sorting algorithm for large datasets, it can be efficient for small datasets or partially sorted arrays due to its adaptive nature.

 

Space Complexity:

The space complexity is determined by the amount of additional memory used by the algorithm as the input size increases. In the above program, the memory usage doesn't increase with the input size. The only variables that are used to perform the sorting and store temporary values are i, key, and j within the insertionSort function. These variables occupy a constant amount of memory, regardless of the size of the input array.

Additionally, the printArray function also uses a constant amount of memory as it only prints the elements of the array and doesn't create any additional data structures.

Since the memory usage remains constant and does not depend on the input size, the space complexity of this program is O(1), indicating constant space usage.

Thank You