BUPT-homework/semester3/pset5/7-1-Insertion-sort.c

42 lines
566 B
C
Raw Normal View History

2022-11-13 21:16:43 +08:00
#include <stdio.h>
void print(int *arr, int N) {
for (int i = 0; i < N; i++) {
printf("%d,", arr[i]);
}
printf("\n");
}
void insertionSort(int *arr, int N) {
int key;
int j;
// i starts at 1.
for (int i = 1; i < N; i++) {
key = arr[i];
j = i;
while (j > 0 && arr[j - 1] > key) {
arr[j] = arr[j - 1];
j--;
}
arr[j] = key;
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]);
}
insertionSort(arr, N);
return 0;
}