[算法入门]C语言实现选择排序

#include "conf.h"

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

    noticeNumber();
    scan(data);

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

conf.h

#include 
#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次比较,所以最坏时间复杂度是O(n2)。
最坏其境况下会进行n-1次交换。

你可能感兴趣的:(算法)