BUPT-homework/semester1/pset10/5-selectsort.c

58 lines
1.4 KiB
C

#include <stdio.h>
//选择排序(升序)
//参数说明:数组,数组中已有元素个数
void selectSort(int data[], int elementCount);
//函数功能:找数组中的最小值元素,并返回其下标
//参数说明:数组名,查找起始位置下标,查找终止位置下标
int findMin(int data[], int startLoc, int endLoc);
//输出数组中所有元素
//参数说明:数组,数组中已有元素个数
void outputData(int data[], int elementCount);
int main() {
int n, i, num[1010];
scanf("%d", &n);
for (i = 0; i < n; i++)
scanf("%d", &num[i]);
selectSort(num, n);
return 0;
}
/* 请在这里填写答案 */
void selectSort(int data[], int elementCount) {
int tmp;
int min;
// Iterate n times
for (int i = 0; i < elementCount - 1; i++) {
// Swap data[i] and data[findMin()]
tmp = data[i];
min = findMin(data, i, elementCount - 1);
/* printf("i: %d, min: %d\n", i, min); */
data[i] = data[min];
data[min] = tmp;
outputData(data, elementCount);
}
}
int findMin(int data[], int startLoc, int endLoc) {
int min = data[startLoc], minloc = startLoc;
for (int i = startLoc; i <= endLoc; i++) {
if (data[i] <= min) {
minloc = i;
min = data[i];
}
}
return minloc;
}
void outputData(int data[], int elementCount) {
for (int i = 0; i < elementCount - 1; i++) {
printf("%d ", data[i]);
}
printf("%d\n", data[elementCount - 1]);
}