C++ Online Compiler
Example: Insertion Sort Descending in C++
C
C++
C#
Java
Python
PHP
main.cpp
STDIN
Run
// Insertion Sort Descending #include <iostream> // Required for input/output operations #include <vector> // Required for using std::vector // Function to print the elements of a vector void printArray(const std::vector<int>& arr) { for (int i = 0; i < arr.size(); ++i) { std::cout << arr[i] << " "; } std::cout << std::endl; } // Function to perform insertion sort in descending order void insertionSortDescending(std::vector<int>& arr) { int n = arr.size(); // Get the number of elements in the array // Iterate from the second element to the end of the array 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 subarray // Move elements of arr[0..i-1], that are smaller 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 previous element in the sorted subarray } arr[j + 1] = key; // Place the key in its correct descending position } } int main() { // Step 1: Initialize an unsorted vector std::vector<int> numbers = {5, 2, 8, 1, 9, 3, 7}; // Step 2: Print the original array std::cout << "Original array: "; printArray(numbers); // Step 3: Perform insertion sort in descending order insertionSortDescending(numbers); // Step 4: Print the sorted array std::cout << "Sorted array (descending): "; printArray(numbers); return 0; // Indicate successful execution }
Output
Clear
ADVERTISEMENTS