Question #265541

Sort the following list using the selection sort algorithm. Show the list after each iteration of the outer for loop. 36, 55, 17, 35, 63, 85, 12, 48, 3, 66


Expert's answer

#include <iostream>
using namespace std;

void PrintArray(int a[], int n) {
    for (int i=0; i<n; i++) {
        cout << a[i] << " ";
    }
    cout << endl;
}

void SortArray(int a[], int n) {
    for (int i=0; i<n-1; i++) {
        int iMin = i;
        for (int j=i+1; j<n; j++) {
            if (a[j] < a[iMin]) {
                iMin = j;
            }
        }
        int tmp = a[iMin];
        a[iMin] = a[i];
        a[i] = tmp;
        PrintArray(a, n);
    }
}

int main() {
    int a[10] = {36, 55, 17, 35, 63, 85, 12, 48, 3, 66};

    cout << "Initial array: ";
    PrintArray(a, 10);
    cout << endl;
    SortArray(a, 10);
    cout << endl;
    cout << "Sorted array: ";
    PrintArray(a, 10);

    return 0;
}
LATEST TUTORIALS
APPROVED BY CLIENTS