【C語言】用選擇法、冒泡法分別對10個整數從小到大排序

【C語言】用選擇法對10個整數從小到大排序:

#include <stdio.h>
#include <stdlib.h>
/* run this program using the console pauser or add your own getch, system("pause") or input loop */

void SelectSort(int array[], int length){
    int i, j, min, temp;
    for(i=0; i<length-1; i++){                                //一共進行length-1趟
        min = i;                                                     //記錄最小元素位置
        for(j=i+1; j<length; j++){                            //在array[i-----n-1]中選擇最小的元素
            if(array[j]<array[min]) min = j;               //更新最小元素位置
        }
        if(min!=i){                                                  //與第i個位置交換
            temp = array[i];
            array[i] = array[min];
            array[min] = temp;
        }
    }
}

int main(int argc, char *argv[]) {
    int array_length = 10;
    int a[array_length];
    int i;
    printf("請輸入10個整數:");
    for(i=0; i<array_length; i++){
        scanf("%d", &a[i]);
    }
    SelectSort(a, array_length);
    printf("排序後的元素爲:\n");
    for(i=0; i<array_length; i++){
        printf("%d ", a[i]);
    }
    printf("\n");
    return 0;
}

 

 

【C語言】用冒泡法對10個整數從小到大排序:

#include <stdio.h>
#include <stdlib.h>
#include <time.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 i, j, a[10], temp;
    printf("請輸入10個整數:");
    for(i=0; i<10; i++){
        scanf("%d", &a[i]);
    }
    for(i=0; i<9; i++){
        for(j=0; j<9; j++){
            if(a[j]>a[j+1]){
                temp = a[j];
                a[j] = a[j+1];
                a[j+1] = temp;
            }
        }
    }
    printf("排序後的數字爲:"); 
    for(i=0; i<10; i++){
        printf("%d ", a[i]);
    }
    return 0;
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章