Ask Your Question
1

How can we use arrays and functions in C++ to implement a selection sort in descending order?

asked 2023-05-05 22:41:25 +0000

ladyg gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
2

answered 2023-05-05 22:43:01 +0000

bukephalos gravatar image

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.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2023-05-05 22:41:25 +0000

Seen: 12 times

Last updated: May 05 '23