简单题目,模拟冒泡排序就行了,开始把问题想复杂了。
#include <stdio.h>
#define MAX_LEN 60
int pos[MAX_LEN]; //pos[i]表示排在位置i的球的号数为pos[i]
void func(int len)
{
int i, j;
int count, t;
count = 0;
for(i=len-1; i>=1; i--)
{
for(j=1; j<=i; j++)
{
if(pos[j] > pos[j+1])
{
t = pos[j];
pos[j] = pos[j+1];
pos[j+1] = t;
count ++;
}
}
}
printf("Optimal train swapping takes %d swaps.\n", count);
}
int main(void)
{
int L, i;
int n;
scanf("%d", &L);
while(L--)
{
scanf("%d", &n);
for(i=1; i<=n; i++)
scanf("%d", pos+i);
func(n);
}
return 0;
}
本文通过简单的冒泡排序实例,详细介绍了排序算法的基本思想、实现过程以及如何优化算法性能,帮助读者掌握基本的排序技巧。

1138

被折叠的 条评论
为什么被折叠?



