1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100
|
#include <cstdlib>
#include <ctime>
#include <iostream>
#include <stdio.h>
#include <string>
#include <vector>
#include <stdlib.h>
#include <array>
using namespace std;
/**
Gets the position of the smallest element in an array range.
@param a the array
@param from the beginning of the range
@param to the end of the range
@return the position of the smallest element in
the range a[from]...a[to]
*/
int min_position(string a[], int from, int to)
{
int min_pos = from;
for (int i = from + 1; i <= to; i++)
{
if (a[i] < a[min_pos]) { min_pos = i; }
}
return min_pos;
}
/**
Swaps two integers.
@param x the first integer to swap
@param y the second integer to swap
*/
void swap(int& x, int& y)
{
int temp = x;
x = y;
y = temp;
}
/**
Sorts a array using the selection sort algorithm
@param a the array to sort
@param size the number of elements in a
*/
void selection_sort(string a[], int size)
{
int next; // The next position to be set to the minimum
for (next = 0; next < size - 1; next++)
{
// Find the position of the minimum starting at next
int min_pos = min_position(a, next, size - 1);
// Swap the next element and the minimum
swap(a[next], a[min_pos]);
}
}
/**
Prints all elements in an array.
@param a the array to print
@param size the number of elements in a
*/
void print(string a[], int size)
{
for (int i = 0; i < size; i++)
{
cout << a[i] << " ";
}
cout << endl;
}
int main()
{
srand(time(0));
const int SIZE = 6;
// changed value to Words
string Words[SIZE]={"School" , "To", "Sky" ,"Grade" , "A","Amazing"};
for(int i = 0; i < SIZE; i++)
{
int index = rand()%SIZE;
string tempword= Words[i];
Words[i]= Words[index];
Words[index]=tempword;
}
print(Words, SIZE);
selection_sort(Words, SIZE);
print(Words, SIZE);
return 0;
}
|