C++ Programming

 

Selection Sort

Program using Selection Sort technique to sort list in Ascending Order


Source Code

#include <iostream.h>

int SelectionSort(int [], int);

int main()
{
const int NUMEL = 10;
int nums[NUMEL] = {22,5,67,98,45,32,101,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 << '\n' << moves << " moves were made to sort this list\n";

return 0;
}


int SelectionSort(int num[], int numel)
{
int i, j, min, minidx, grade, moves = 0;

for ( i = 0; i < (numel - 1); i++)

{

min = num[i]; // assume minimum is the first array element
minidx = i; // index of minimum element

for(j = i + 1; j < numel; j++)
{
if (num[j] < min) // if we've located a lower value
{ // capture it
min = num[j];
minidx = j;
}
}
if (min < num[i]) // check if we have a new minimum
{ // and if we do, swap values
grade = num[i];
num[i] = min;
num[minidx] = grade;
moves++;
}
}

return moves;
}

 


DISCLAIMER

Paked and the contributors are not responsible for any errors contained and are not liable for any damages resulting from the use of this material.  (Disclaimer)

 

 

Home     Disclaimer     Advertise      Contact us     

Copyright © 2006-08 Paked.com. All rights reserved.

Note: Site best viewed at 1024 x 768 or higher screen resolution

 

footer image footer image