Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

Here is an example implementation of selection sort in descending order using arrays and functions in C++:

#include <iostream>
using namespace std;

void selectionSort(int arr[], int size) {
    for (int i = 0; i < size - 1; i++) {
        int maxIndex = i;
        for (int j = i + 1; j < size; j++) {
            if (arr[j] > arr[maxIndex]) {
                maxIndex = j;
            }
        }
        swap(arr[i], arr[maxIndex]);
    }
}

int main() {
    int myArray[] = {5, 2, 9, 1, 7, 3};
    int arraySize = sizeof(myArray) / sizeof(myArray[0]);

    selectionSort(myArray, arraySize);

    for (int i = 0; i < arraySize; i++) {
        cout << myArray[i] << " ";
    }
    cout << endl;

    return 0;
}

In this implementation, the selectionSort function takes an array of integers and its size as input parameters. It uses two nested loops to find the maximum element in the unsorted portion of the array and swap it with the first element in the unsorted portion. This process repeats until the entire array is sorted in descending order.

The main function declares an integer array and its size, calls the selectionSort function to sort the array, and outputs the sorted array to the console. Note that the swap function is used to swap two elements in the array.