選擇冒泡排序

1、選擇排序

  (1)、算法思想:依次是下標爲(0,1,2,....n)的數字和其後的所有數字進行比較,每一輪的比較結果:都先確定最前面的是最小的數字;

  (2)、代碼實現

#include<stdio.h>

void sort(int *a, int count);
void showArray(int *a, int count);

void showArray(int *a, int count){
    int i;

    for(i = 0; i < count; i++){
        printf("%d ", a[i]);    
    }
    printf("\n");
}

void sort(int *a, int count){
    int i;
    int j;
    int tmp;

    for(i = 0; i < count; i++){
        for(j = i+1; j < count; j++){
            if(a[i] > a[j]){
                tmp = a[i];
                a[i] = a[j];
                a[j] = tmp;
            }
        }
    }
}

void main(void){
    int a[] = {3 ,5 ,6, 1, 7, 2, 9, 8};
    int count = sizeof(a)/sizeof(int);

    sort(a, count);
    showArray(a, count);
}

  (3)、結果打印

wKioL1iluzagS8axAAAUHPuSkW4217.png-wh_50

  (4)、算法分析

  時間複雜度爲:O(n^2);


2、交換(冒泡)排序

  (1)、算法思想:相鄰的2個數字,兩兩進行比較,每一輪的排序結果:最大的數字在最後面的位置;

  (2)、代碼實現

#include<stdio.h>

void swapSort(int *a, int count);
void showArray(int *a, int count);

void showArray(int *a, int count){
    int i;

    for(i = 0; i < count; i++){
        printf("%d ", a[i]);
    }

    printf("\n");
}

void swapSort(int *a, int count){
    int i;
    int j;
    int tmp;

    for(i = 0; i < count; i++){
        for(j = 0; j < count-i; j++){
            if(a[j] > a[j+1]){ //將大的數字放在最後面
                tmp = a[j];
                a[j] = a[j+1];
                a[j+1] = tmp;
            }
        }
    }
}

void main(void){
    int a[] = {3, 5, 7, 9, 1, 6, 10};
    int count = sizeof(a)/sizeof(int);

    swapSort(a, count);
    showArray(a, count);
}

  (3)、結果截圖

wKiom1ilvo_zo522AAAUd1lMzJA027.png-wh_50

  (4)、算法分析

  時間複雜度:O(n^2);




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