Selection Sort (descending)

Lab C Intermediate 20 points

Sort n integers in descending order using selection sort, printing the array after each swap that changes it.

Input

Line 1: n. Line 2: n integers.

Output

The array after each swap, then the final array.

Example

Input

5
3 1 4 1 5

Output

5 1 4 1 3
5 4 1 1 3
5 4 3 1 1
5 4 3 1 1
Sample input available Sample output available
Editor
C

Hints

Find the largest remaining element and swap it into position i.

Solution explanation

Selection sort makes at most n − 1 swaps, which matters when swapping is expensive.

Show solution
#include <stdio.h>

void print_array(int *a, int n) {
    for (int i = 0; i < n; i++) {
        printf("%d", a[i]);
        if (i < n - 1) printf(" ");
    }
    printf("\n");
}

int main() {
    int n, a[100];
    scanf("%d", &n);
    for (int i = 0; i < n; i++) scanf("%d", &a[i]);
    for (int i = 0; i < n - 1; i++) {
        int best = i;
        for (int j = i + 1; j < n; j++) {
            if (a[j] > a[best]) best = j;
        }
        if (best != i) {
            int t = a[i];
            a[i] = a[best];
            a[best] = t;
            print_array(a, n);
        }
    }
    print_array(a, n);
    return 0;
}
Output
Answer
HOME LEARN COMMUNITY DASHBOARD