交換時,兩個 carriages 交換。目標是要由小排到大,這邊要做的就是 bubble sort。
#include <stdio.h>
#include <stdlib.h>
int main(void){
int amount,i,j,tmp,counter;
int length,carriage[51]={0};
scanf("%d",&amount);
while(amount--){
scanf("%d",&length);
for(i=0;i<length;i++) scanf("%d",&carriage[i]);
counter=0;
for(i=0;i<length;i++){
for(j=0;j<length-1-i;j++){
if(carriage[j]>carriage[j+1]){
tmp=carriage[j];
carriage[j]=carriage[j+1];
carriage[j+1]=tmp;
++counter;
}
}
}
printf("Optimal train swapping takes %d swaps.\n",counter);
}
return 0;
}
沒有留言:
張貼留言