C Online Compiler
Example: Insertion Sort in C
C
C++
C#
Java
Python
PHP
main.c
STDIN
Run
// Insertion Sort #include <stdio.h> // Function to print an array void printArray(int arr[], int size) { for (int i = 0; i < size; i++) { printf("%d ", arr[i]); } printf("\n"); } // Function to perform insertion sort void insertionSort(int arr[], int n) { // Step 1: Iterate from the second element (index 1) to the end of the array for (int i = 1; i < n; i++) { // Step 2: Store the current element to be inserted int key = arr[i]; // Step 3: Initialize j to the index of the element just before 'key' int j = i - 1; // Step 4: 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 = j - 1; } // Step 5: Place the key at its correct position in the sorted sub-array arr[j + 1] = key; printf("Pass %d: ", i); printArray(arr, n); } } int main() { int arr[] = {12, 11, 13, 5, 6}; int n = sizeof(arr) / sizeof(arr[0]); printf("Original array: "); printArray(arr, n); insertionSort(arr, n); printf("Sorted array: "); printArray(arr, n); return 0; }
Output
Clear
ADVERTISEMENTS