44 lines
859 B
C
44 lines
859 B
C
|
#include <stdio.h>
|
||
|
|
||
|
//插入排序(升序)
|
||
|
//参数说明:数组,数组中已有元素个数
|
||
|
void InsertSort(int a[], int n);
|
||
|
|
||
|
int main() {
|
||
|
int n, i, num[1000];
|
||
|
|
||
|
scanf("%d", &n);
|
||
|
for (i = 0; i < n; i++)
|
||
|
scanf("%d", &num[i]);
|
||
|
InsertSort(num, n);
|
||
|
return 0;
|
||
|
}
|
||
|
|
||
|
/* 请在这里填写答案 */
|
||
|
void InsertSort(int a[], int n) {
|
||
|
int loc;
|
||
|
int selected;
|
||
|
// sorted subarray: a[0 ~ i - 1]
|
||
|
for (int i = 1; i < n; i++) {
|
||
|
selected = a[i];
|
||
|
loc = 0;
|
||
|
for (int j = 0; j < i; j++) {
|
||
|
if (a[j] <= selected) {
|
||
|
loc = j + 1;
|
||
|
}
|
||
|
}
|
||
|
// switch to location
|
||
|
/* printf("location: %d i: %d\n", loc, i); */
|
||
|
for (int j = i; j > loc; j--) {
|
||
|
a[j] = a[j - 1];
|
||
|
}
|
||
|
a[loc] = selected;
|
||
|
// print array
|
||
|
for (int j = 0; j < n - 1; j++) {
|
||
|
printf("%d ", a[j]);
|
||
|
}
|
||
|
printf("%d\n", a[n - 1]);
|
||
|
}
|
||
|
return;
|
||
|
}
|