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.
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
Asked: 2023-05-05 22:41:25 +0000
Seen: 12 times
Last updated: May 05 '23
What is the method to get a printable output of a C++11 time_point?
What is the process of redefining a c++ macro with fewer parameters?
How can a list be sorted alphabetically within a console application?
How can boost c++11 be used to resolve the symlinks of a file path?
What distinguishes the jsonlite and rjson packages from each other at their core?
How can the issue of accessing a member within an address that is misaligned be resolved at runtime?
Does a C++ constructor get passed down through inheritance?
What is the difference between deallocating memory in C and deallocating memory in C++?