How to sort an array in descending order using selection sort with C++

1 Answer

0 votes
#include <iostream>

void selectionSortDescending(int arr[], int n) {
    for (int i = 0; i < n - 1; i++) {
        int maxIdx = i;
        for (int j = i + 1; j < n; j++) {
            if (arr[j] > arr[maxIdx]) {
                maxIdx = j;
            }
        }
        // Swap the found maximum element with the i element
        int temp = arr[maxIdx];
        arr[maxIdx] = arr[i];
        arr[i] = temp;
    }
}

int main() {
    int arr[] = {2, 141, 3, 4, 21, 13, 30, 50};
    int n = sizeof(arr) / sizeof(arr[0]);

    selectionSortDescending(arr, n);

    for (int i = 0; i < n; i++) {
        std::cout << arr[i] << " ";
    }
}



/*
run:
     
141 50 30 21 13 4 3 2 
     
*/
 

 



answered Feb 26, 2025 by avibootz

Related questions

...