#include<iostream> using namespace std;
// return the index of the minimun after startIndex int minIndex(int a[], int size, int startIndex);
// swap the content of 2 integers. void swap(int& a, int& b);
// sort the array use selection sort void sort(int a[], int size);
// display the array void display(int a[], int size);
int main() { int a[] = {8,6,10,2,16,4,18,14,12,20}; cout << "Before sorting: \n"; display(a,10); cout << endl; sort(a, 10); cout << "After sorting: \n"; display(a,10); cout << endl;
return 0; }
int minIndex(int a[], int size, int startIndex) { int min = a[startIndex]; // assume the first one is the min int minInd = startIndex; for(int i = startIndex + 1; i < size; i++) { if(min > a[i]) { // a[i] is actually smaller minInd = i; min = a[i]; } } return minInd; }
void swap(int& a, int& b) { int temp = a; a = b; b = temp; }
void sort(int a[], int size) { for(int i = 0; i < size; i++) { int minInd = minIndex(a, size, i); // swap a[i] and a[minInd] swap(a[i], a[minInd]); } }
void display(int a[], int size) { for(int i = 0; i < size; i++) { cout << a[i] << " "; } }
|