C Online Compiler
Example: Insertion Sort in Descending Order in C
C
C++
C#
Java
Python
PHP
main.c
STDIN
Run
// Insertion Sort in Descending Order #include <stdio.h> // Function to perform insertion sort in descending order void insertionSortDescending(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; // Index of the last element in the sorted subarray // Move elements of arr[0..i-1], that are smaller than key, // to one position ahead of their current position. // This creates space for 'key' at the correct descending position. while (j >= 0 && arr[j] < key) { // Changed from arr[j] > key for ascending arr[j + 1] = arr[j]; j = j - 1; } arr[j + 1] = key; // Place key at its correct position } } // Function to print an array void printArray(int arr[], int size) { for (int i = 0; i < size; i++) { printf("%d ", arr[i]); } printf("\n"); } int main() { // Step 1: Initialize an unsorted array int arr[] = {12, 11, 13, 5, 6}; int n = sizeof(arr) / sizeof(arr[0]); printf("Original array: "); printArray(arr, n); // Step 2: Call the insertion sort function for descending order insertionSortDescending(arr, n); printf("Sorted array (descending): "); printArray(arr, n); return 0; }
Output
Clear
ADVERTISEMENTS