Selection Sort
Binary Search |
Bubble Sort |
Selection Sort |
Finding Maximum Value |
Linear Search |
Celsius to Fahrenheit |
10 Pseudo-random numbers |
Calculating Average |
Swapping Values |
Lowercase/ Uppercase
Program
using Selection Sort to sort list in
Ascending Order
C++ 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;
}
Copyrights
Gary Bronson. "A First Book of C++: From
Here to There " Thomson Learning.
|