....

2014年5月20日 星期二

[長知識] C語言 - 新手篇章 - 排序法 - 氣泡排序法

#include <stdio.h>
#include <stdlib.h>

/* run this program using the console pauser or add your own getch, system("pause") or input loop */

int main(int argc, char *argv[]) {

//排序法 - 氣泡排序法

int num[] = {2, 8,7,30, 14, 66, 95,100, 1};
int sortsize = sizeof(num)/sizeof(int);
int i, j, k;



//i< sortsize -1 : 沒有必要判斷到最後
for(i =0 ;i< sortsize -1 ; i++){

// j =i+1 : 沒有必要跟自己判斷
for(j =i+1; j<sortsize; j++){

//最小的拉到最前面
if(num[i]>num[j]){
int temp = num[i];
num[i] = num[j];
num[j] = temp;

}
}
}

for(k=0 ; k<sortsize ;k++){
     printf("%i\n", num[k]);
}

return 0;
}

沒有留言:

張貼留言