C Online Compiler
Example: Simple Insertion Sort in C
C
C++
C#
Java
Python
PHP
main.c
STDIN
Run
// Simple 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) { int i, key, j; for (i = 1; i < n; i++) { key = arr[i]; // Store the current element to be inserted j = i - 1; // Start comparing with the element just before 'key' // 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]; // Shift element to the right j = j - 1; // Move to the left to compare next element } arr[j + 1] = key; // Place key in its correct position } } int main() { // Step 1: Define an array int arr[] = {12, 11, 13, 5, 6}; int n = sizeof(arr) / sizeof(arr[0]); // Calculate size of the array // Step 2: Print the original array printf("Original array: "); printArray(arr, n); // Step 3: Perform insertion sort insertionSort(arr, n); // Step 4: Print the sorted array printf("Sorted array (ascending): "); printArray(arr, n); return 0; }
Output
Clear
ADVERTISEMENTS