C Online Compiler
Example: Insertion Sort without Functions in C
C
C++
C#
Java
Python
PHP
main.c
STDIN
Run
// Insertion Sort without Functions #include <stdio.h> // Required for input/output operations int main() { // Step 1: Declare and initialize the array int arr[] = {12, 11, 13, 5, 6}; int n = sizeof(arr) / sizeof(arr[0]); // Calculate the number of elements printf("Original array: "); for (int i = 0; i < n; i++) { printf("%d ", arr[i]); } printf("\n"); // Step 2: Implement the Insertion Sort logic // Start from the second element (index 1) as the first element // is considered already sorted in a sub-array of size 1. for (int i = 1; i < n; i++) { int key = arr[i]; // Store the current element to be inserted int j = i - 1; // Initialize j to the last element of the sorted sub-array // 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 in the sorted sub-array } arr[j + 1] = key; // Place the key in its correct position } // Step 3: Print the sorted array printf("Sorted array: "); for (int i = 0; i < n; i++) { printf("%d ", arr[i]); } printf("\n"); return 0; // Indicate successful execution }
Output
Clear
ADVERTISEMENTS