C Online Compiler
Example: Insertion Sort Algorithm in C
C
C++
C#
Java
Python
PHP
main.c
STDIN
Run
// Insertion Sort Algorithm #include <stdio.h> void insertionSort(int arr[], int n) { int i, key, j; for (i = 1; i < n; i++) { key = arr[i]; // Current element to be inserted j = i - 1; // Start comparing with the element before the current one // 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; } arr[j + 1] = key; // Place key at its correct position } } void printArray(int arr[], int n) { for (int i = 0; i < n; i++) { printf("%d ", arr[i]); } printf("\n"); } int main() { // Step 1: Define an unsorted array int arr[] = {12, 11, 13, 5, 6}; int n = sizeof(arr) / sizeof(arr[0]); // Step 2: Print the original array printf("Original array: "); printArray(arr, n); // Step 3: Apply insertion sort insertionSort(arr, n); // Step 4: Print the sorted array printf("Sorted array: "); printArray(arr, n); return 0; }
Output
Clear
ADVERTISEMENTS