[英]About the Bubble Sort in C
這是我的代碼:
//bubble sort
#include<stdio.h>
int main(){
int a[11];
int temp;
int i,j;
//input
for(i=1;i<=10;i++){
scanf("%d",&a[i]);
}
//sort
for(i=1;i<10;i++){ //the number of number
for(j=1;j<10-i;j++) //--
if(a[j]<a[j+i]){
temp=a[j];
a[j]=a[j+1];
a[j+1]=temp;
}
}
//output
for(i=1;i<=10;i++){
printf("%d ",a[i]);
}
getchar();
getchar();
return 0;
}
結果不是我所期待的。 我使用的輸入是1 2 3 4 5 6 7 8 9 0但排序后輸出為8 6 5 4 3 7 2 9 1 0。
兩件事情:
一個錯字(我相信):
if(a[j]<a[j+i]){
本來應該
if(a[j]<a[j+1]){
其次,
for(j=1;j<10-i;j++)
本來應該
for(j=1;j<10-i+1;j++)
您需要額外運行一次循環,以適應所有交換。
請注意,數組是基於零的 - 你應該在所有實例中啟動i = 0
- 似乎你只需要10個數字,所以每次迭代需要從0..9
和int a[10];
數組int a[10];
就足夠了。
假設您希望從最低到最高排序的bubblesort輸出,算法應該是:
for(i=0; i < 10; i++){
for(j=0; j < 10 - i - 1; j++) // Because we are looking ahead one cell, -1
if(a[j] > a[j+1]){ // next cell
temp=a[j];
a[j]=a[j+1];
a[j+1]=temp;
}
}
意思是,在第一遍之后,最高的數字將在a[9]
。 下一個循環將在a[8]
設置下一個最高點。 等等
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.