BUPT-homework/semester3/pset5/7-4-Selection-Sort.c

44 lines
684 B
C
Raw Permalink Normal View History

2022-11-13 21:16:43 +08:00
#include <stdio.h>
void swap(int *arr, int l, int r) {
int tmp = arr[l];
arr[l] = arr[r];
arr[r] = tmp;
}
void print(int *arr, int N) {
for (int i = 0; i < N; i++) {
printf("%d,", arr[i]);
}
printf("\n");
}
void selectionSort(int *arr, int N) {
for (int i = 0; i < N - 1; i++) {
int min = arr[i];
int minIndex = i;
for (int j = i + 1; j < N; j++) {
if (arr[j] < min) {
min = arr[j];
minIndex = j;
}
}
swap(arr, minIndex, i);
print(arr, N);
}
}
int main(void) {
int N;
scanf("%d", &N);
int arr[N];
for (int i = 0; i < N; i++) {
scanf("%d,", &arr[i]);
}
selectionSort(arr, N);
return 0;
}