[算法入門]C語言實現冒泡排序

#include "conf.h"

int main(){
                int i                   = 0;
                int data[10]    = {0};
                int j                   = 0;

        noticeNumber();
        scan(data);

        for(i=0; i<COUNT; i++){
                                for(j=0; j<COUNT-i-1; j++){
                                                swap(&data[j], &data[j+1]);
                                }
                }

       printResult(data);
}

#include <stdio.h>
#define COUNT   5 // The number of the numbers
#define FALSE   0
#define TRUE    1
typedef int     BOOL;

/* Print the information that user should input how many number */
void noticeNumber(){
    printf("please input %d number\n", COUNT);
}

/* get the series that need sort*/
void scan(int *data){
    int i;

    for(i=0; i<COUNT; i++){
        scanf("%d", data+i);
    }
}

/*print the result */
int printResult(int *data){
    int i;

    printf("The result is:\n");
    for(i=0; i<COUNT; i++){
        printf("%d ", data[i]);
    }

    printf("\n");
}

/* Swap two sort */
int swap(int *number1, int *number2){
                int temp = 0;

                if(*number1<=*number2)
                                return 0;
                else{
                                temp = *number1;
                                *number1 = *number2;
                                *number2 = temp;
                }
}

時間複雜度

最壞情況下會進行(n-1)(1+n-1)/2次交換即n(n-1)/2次比較,所以它的時間複雜度是O(n2)。
最壞情況下會進行3*(n-1)*n/2次交換。

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