Thursday, 3 March 2016

Rewrite the Selection Sort function so that it performs a descending sort

Leave a Comment
Questions:

Rewrite the Selection Sort function so that it performs a descending sort

Explanation:

Below mention code is compiled in Visual Studio 2015 and Code Blocks 13.12,output snap is attached.. If any problem you feel and you want some explanation feel free to contact us.

Code:

/**************************************************|
/*************C++ Programs And Projects************|
***************************************************/
#include<iostream>
using namespace std;

void selectionSort(int[], int);//Function Prototype
void main() {
       int arra[5] = { 3,4,1,2,5 };
       cout << "Given Data" << endl;
       for (int i = 0; i < 5; i++) {
              cout << arra[i]<<"   ";
       }
       cout << endl;
       selectionSort(arra, 5);
       cout << "After Sorting Data" << endl;
       for (int i = 0; i < 5; i++) {
              cout << arra[i] << "   ";
       }
       cout << endl;
}


void selectionSort(int arr[], int size)
{
       for (int i = 0; i < size - 1; i++)//we need to do size-2 passes
       {
              int iMin = i;
              for (int j = i + 1; j < size; j++)
              {
                     if (arr[j] > arr[iMin]) {
                           iMin = j;
                     }
              }
              //swaping
              int temp = arr[i];
              arr[i] = arr[iMin];
              arr[iMin] = temp;
       }
}



Output:


Related Articles:

Sorting Algorithms

If You Enjoyed This, Take 5 Seconds To Share It