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
|
#include <iostream>
using namespace std;
int findIndexOfMax(int A[], int start, int end);
void swap(int A[], int index1, int index2);
int main()
{
int n;
cout << "Give number of integers to sort: ";
cin >> n;
// Input validation
if (n > 100)
{
cout << "Too many elements!" << endl;
return -1;
}
if (n <= 0)
{
cout << "Invalid input!" << endl;
return -1;
}
int count, A[100];
// Array of integers to sort
// Read integers to sort
cout << "Give " << n << "integers to sort." << endl;
for (count = 0; count < n; count++)
{
cin >> A[count];
}
int currTop, currMaxIndex;
// A[currTop] … A[n-1] is unsorted array
for (currTop = 0; currTop < n; currTop ++)
{
currMaxIndex = findIndexOfMax(A, currTop, n);
swap(A, currTop, currMaxIndex);
cout << "new order is " << currMaxIndex << endl;
}
return 0;
}
int findIndexOfMax(int A[], int start, int end)
{
int i, currMaxIndex = start;
for ( i = start ; i < end; i++ )
{
if (A[i] >= A[currMaxIndex])
{
currMaxIndex = i;
}
}
return currMaxIndex;
}
void swap(int A[], int index1, int index2)
{
int temp;
temp = A[index1];
A[index1] = A[index2];
A[index2] = temp;
return;
}
|