C++ Array selection sort

Description

C++ Array selection sort

#include <iostream>
using namespace std;
int selectionSort(int [], int);
int main()//from   w  ww .  j  a va  2 s. co m
{
   const int NUMEL = 10;
   int nums[NUMEL] = {2,5,7,9,4,32,11,99,73,10};
   int i, moves;
   moves = selectionSort(nums, NUMEL);
   cout << "The sorted list, in ascending order, is:\n";
   for (i = 0; i < NUMEL; i++)
      cout << "  " << nums[i];
   cout << endl << moves << " moves were made to sort this list\n";
   return 0;
}
int selectionSort(int num[], int numel)
{
   int i, j, min, minidx, temp, moves = 0;
   for (i = 0; i < (numel - 1); i++)
   {
      min = num[i];
      minidx = i;
      for (j = i + 1; j < numel; j++)
      {
         if (num[j] < min)
         {
            min = num[j];
            minidx = j;
         }
      }
      if (min < num[i])
      {
         temp = num[i];
         num[i] = min;
         num[minidx] = temp;
         moves++;
      }
   }
   return moves;
}



PreviousNext

Related