📜  c语言中询问用户输入的冒泡排序 - C编程语言代码示例

📅  最后修改于: 2022-03-11 15:04:42.505000             🧑  作者: Mango

代码示例1
#include 
#include 

typedef enum _order {
    Ascending=1, Descending
} order;

void swap(int *x, int *y){
    int wk;
    wk=*x;*x=*y;*y=wk;
}

int needSwap(int x, int y, order dir){
    if(dir == Ascending)
        return x > y;
    if(dir == Descending)
        return x < y;
    return 0;
}

void bubbleSort(int *array, int top, int end, order dir){
    int i, j, swaped;
    for(i = top; i < end; ++i){
        swaped = 0;
        for(j = top + 1; j <= end - i; ++j)
            if(needSwap(array[j-1], array[j], dir)){
                swap(&array[j-1], &array[j]);
                swaped = 1;
            }
        if(swaped == 0)break;
    }
}

int main(){
    int myarray[100], index, order;
    index=0;
    printf("Enter your numbers. Write -1 to stop. \n");
    do{
        scanf("%d", &myarray[index++]);
    }while(myarray[index-1] != -1 && index < 100);
    --index;//Correction to point to the final value
    printf("Enter 1 if you want them to be in ascending order.\n"
           "Enter 2 if you want descending order\n");
    scanf("%d",&order);
    bubbleSort(myarray, 0, index-1, order);
    {//result print
        int i;
        for(i=0;i