C Online Compiler
Example: Insertion Sort using Function in C
C
C++
C#
Java
Python
PHP
main.c
STDIN
Run
// Insertion Sort using Function #include <stdio.h> // Required for input/output operations // Function to print an array void printArray(int arr[], int size) { // Step 1: Iterate through the array from the first element to the last for (int i = 0; i < size; i++) { // Step 2: Print each element followed by a space printf("%d ", arr[i]); } // Step 3: Print a newline character to move to the next line printf("\n"); } // Function to perform insertion sort on an array void insertionSort(int arr[], int size) { // Step 1: Outer loop to iterate from the second element to the last element // The first element (index 0) is considered already sorted for (int i = 1; i < size; i++) { // Step 2: Store the current element to be inserted in its correct position int key = arr[i]; // Step 3: Initialize 'j' to the index of the element just before 'key' int j = i - 1; // Step 4: Inner loop to shift 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 with the next element } // Step 5: Place the 'key' (current element) in its correct sorted position arr[j + 1] = key; } } int main() { // Step 1: Declare and initialize an unsorted integer array int arr[] = {12, 11, 13, 5, 6}; // Step 2: Calculate the size of the array int size = sizeof(arr) / sizeof(arr[0]); // Step 3: Print the original array printf("Original array: "); printArray(arr, size); // Step 4: Call the insertionSort function to sort the array insertionSort(arr, size); // Step 5: Print the sorted array printf("Sorted array: "); printArray(arr, size); return 0; // Indicate successful execution }
Output
Clear
ADVERTISEMENTS