之前一直不怎么看得懂雙重的for循環(huán),以至于寫最基礎(chǔ)的兩個選擇方式的時候總不能一筆喝成。今天突有靈感,來寫寫看。
把大的往左移動一位,移動 j 次,分 i 趟
冒泡排序
for(int i = 0; i < n; i++){
for(int j = 0; j<n-1-i; j++){
if( a[j] > a[j+1]){
int temp = a[j];
a[j] = a[j+1];
a[j+1] = temp;
}
}
}
【我在想怎么用scanf()函數(shù)手動輸入數(shù)組內(nèi)容,
#include<cstdio>
int main()
{
int a[5];
for(int i=0;i<5;i++){
scanf("%d",&a[i]);
}
for(int i = 0; i < 5; i++){
for(int j = 0; j < i; j++){
if( a[j] > a[j+1]){
int temp = a[j];
a[j] = a[j+1];
a[j+1] = temp;
}
}
}
for(int j=0;j<5;j++){
printf("%d",a[j]);
}
return 0;
}
這段代碼運行不出來?!?/p>
選擇排序
for(int i=0;i<4;i++){
int k=i;
for(int j=i+1;j<5;j++){
if(a[k]>a[j]){
k=j;
}
int temp=a[k];
a[k]=a[i];
a[i]=temp;
}
}