C++ Online Compiler
Example: Selection Sort Descending in C++
C
C++
C#
Java
Python
PHP
main.cpp
STDIN
Run
// Selection Sort Descending #include <iostream> #include <vector> // Using vector for dynamic array, can be adapted for static arrays #include <algorithm> // For std::swap // Function to print the array void printArray(const std::vector<int>& arr) { for (int num : arr) { std::cout << num << " "; } std::cout << std::endl; } int main() { // Step 1: Initialize an unsorted array std::vector<int> arr = {64, 25, 12, 22, 11}; int n = arr.size(); std::cout << "Original array: "; printArray(arr); // Step 2: Implement Selection Sort for descending order // Iterate through the array from the first element to the second-to-last for (int i = 0; i < n - 1; ++i) { // Assume the current element is the maximum int max_idx = i; // Find the index of the actual maximum element in the unsorted part (from i+1 to n-1) for (int j = i + 1; j < n; ++j) { // If we find an element greater than the current maximum, update max_idx if (arr[j] > arr[max_idx]) { max_idx = j; } } // Step 3: Swap the found maximum element with the element at the current position 'i' // This places the largest element in its correct position (beginning of the unsorted part) if (max_idx != i) { std::swap(arr[i], arr[max_idx]); } std::cout << "Array after pass " << i + 1 << ": "; printArray(arr); } // Step 4: Display the sorted array std::cout << "Sorted array (descending): "; printArray(arr); return 0; }
Output
Clear
ADVERTISEMENTS