Implementing Selection Sort with Step-by-Step Output
Selection Sort Algorithm Implementation
This program implements the selection sort algorithm to sort an array of integers in ascending order, displaying the array state after each sorting step.
Input Format
The first line contains a positive integer n (n ≤ 10). The second line contains n integres separated by spaces.
Output Format
After each sorting step, output the current state of the array from index 0 to n-1, with elements separated by spaces and no trailing spaces.
Example Input
4
5 1 7 6
Example Output
1 5 7 6
1 5 7 6
1 5 6 7
Implemantation Code
#include <stdio.h>
void displayArray(int arr[], int size) {
for (int i = 0; i < size; i++) {
if (i > 0) printf(" ");
printf("%d", arr[i]);
}
printf("\n");
}
int main() {
int count;
scanf("%d", &count);
int numbers[count];
for (int i = 0; i < count; i++) {
scanf("%d", &numbers[i]);
}
if (count == 1) {
printf("%d\n", numbers[0]);
return 0;
}
for (int current = 0; current < count - 1; current++) {
int minIndex = current;
for (int j = current + 1; j < count; j++) {
if (numbers[j] < numbers[minIndex]) {
minIndex = j;
}
}
int temp = numbers[minIndex];
numbers[minIndex] = numbers[current];
numbers[current] = temp;
displayArray(numbers, count);
}
return 0;
}