...
/Solution Review: Sort Elements of an Array in Descending Order
Solution Review: Sort Elements of an Array in Descending Order
Let's go over the solution review of the challenge given in the previous lesson.
We'll cover the following...
Solution #
Press the RUN button and see the output!
Press + to interact
#include <iostream>using namespace std;// sort_elements functionvoid sort_elements(int arr[], int size) {// Outer loopfor (int i = 0; i < size; i++) {// Inner loopfor (int j = i + 1; j < size; j++) {// If conditionif (arr[i] < arr[j]) {// Swap elements// Store the value at index j in tempint temp = arr[j];// Store the value at index i at index jarr[j] = arr[i];// Store the value of temp at index iarr[i] = temp;}}}}// Function to print values of an arrayvoid print_array(int arr[], int size) {// Traverse arrayfor (int i = 0; i < size; i++) {// Print value at index icout << arr[i] << " ";}cout << endl;}// main functionint main() {// Initialize size of an arrayint size = 4;// Initialize array elementsint arr[size] = {10, 67, 98, 31};cout << "Array before sorting: " << endl;// Call print_array functionprint_array(arr, size);// Call sort_elements functionsort_elements(arr, size);cout << "Array after sorting: " << endl;// Call print_array functionprint_array(arr, size);return 0;}
Explanation
To sort elements in descending order, we compare the first element of an array with the rest of the ...