最近看C语言有点烦,无论是自学的数据结构还是学校的指针课程,看着头都大了。
学校在PTA安排了此题,提交了多次总是报错,今天重新整理一遍且不按题目编程提示来写,提交终于正确。
(其实是最后一个数字不能有空格,而题目没有说明白)
将此题记录一下,说不定某些小伙伴需要呢?
此题可能不是标准答案,仅作参考。
Enter 10 integers for sorting and output. Use a function pointer to write a general sorting function. If you enter 1, the program will sort data in ascending order; if you enter 2, the program will sort data in descending order.
Input example 1:
Input data, separated by spaces.
Input sample 1:
2 3 4 9 10 8 7 6 5 1
1
Output sample 1: The
output format The data format is as follows, separated by a space.
Output sample 1:
1 2 3 4 5 6 7 8 9 10
Input example 2:
2 3 4 9 10 8 7 6 5 1
2
Sample output 2:
10 9 8 7 6 5 4 3 2 1
#include <stdio.h>
void sort_1(int a[], int n)
{
int i, j, * p = a;
for (i = 0; i < n - 1; i++)
{
for (j = i + 1; j < n; j++)
{
if (*(p + i) > * (p + j)) //升序
{
int t;
t = *(p + i);
*(p + i) = *(p + j);
*(p + j) = t;
}
}
}
}
void sort_2(int a[], int n)
{
int i, j, * p = a;
for (i = 0; i < n - 1; i++)
{
for (j = i + 1; j < n; j++)
{
if (*(p + i) < * (p + j)) //降序
{
int t;
t = *(p + i);
*(p + i) = *(p + j);
*(p + j) = t;
}
}
}
}
int main()
{
int i, j, a[10];
for (j = 0; j < 10; j++)
scanf("%d", &a[j]);
int flag;
scanf("%d", &flag);
switch (flag)
{
case 1:
sort_1(a, 10);
break;
case 2:
sort_2(a, 10);
break;
}
printf("%d", *(a));
for (i = 1; i < 10; i++)
printf(" %d", *(a + i));
return 0;
}