题解 | #特殊排序#
特殊排序
https://www.nowcoder.com/practice/57f0f528bff149be9580af66f6292430
#include <stdio.h>
#define Nmax 1000
//use BubbleSort
//1.sorted
//2.max is easy to find
//3.other point
//how to input?use array to get a list[]
//how to output 1~N-1
//指向数组的指针、指向数组元素的指针,如何表示数组元素
// 因为出来后仍对排序后数组有操作,传入指针保存修改
//1.进行len(numList)-1次冒泡
//2.首次进行len(numList)-1次冒交换,并--
//错误点(*pList)[j-1]
// (*pList)表示的是List[0],理解为pList=numList,所以numList怎么用pList就怎么用
//pList[i]=*(pList+i)
//int *pList也可以写成int pList[]
void BubbleSort(int* pList, int N) {
int i, j, temp;
for (i = 0; i < N - 1; i++) {
// 每轮比较的次数
for (j = 1; j <= N - 1 - i; j++) {
//自己选择升序还是降序
//本代码为从左到右边升序
if (pList[j - 1] > pList[j]) {
temp = pList[j];
pList[j] = pList[j - 1];
pList[j - 1] = temp;
}
}
}
}
int main() {
int N, i;
int numList[Nmax];
//1.input
scanf("%d", &N);
for (i = 0; i < N; i++) {
scanf("%d", &numList[i]);
}
//2.func
//传递数组其实就是有效地传递指向其第一个元素的指针
BubbleSort(numList, N);
//3.output
printf("%d\n", numList[N - 1]);
if (N == 1) {
printf("-1");
} else {
for (i = 0; i < N - 1; i++) {
printf("%d ", numList[i]);
}
}
}
查看11道真题和解析