Search
 
SCRIPT & CODE EXAMPLE
 

C

buble sort in c that ask user input

#include <stdio.h>
#include <stdlib.h>

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. 
");
    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.
"
           "Enter 2 if you want descending order
");
    scanf("%d",&order);
    bubbleSort(myarray, 0, index-1, order);
    {//result print
        int i;
        for(i=0;i<index;++i)
            printf("%d ", myarray[i]);
        printf("
");
    }
    system("PAUSE");
    return 0;
}
Comment

PREVIOUS NEXT
Code Example
C :: disable gnu++11 option 
C :: georgia institute of technology 
C :: c to assembly converter online 
C :: c math.h sqrt 
C :: injection 
C :: bc1q9rfht42zayr3yvxqjw8tm6v3tkwl93t35gegxl 
C :: como hacer para que una salida en linux aparezca de poco en poco 
C :: pre-commit configuration 
C :: assembly to c code converter 
C :: determination data type in c 
C :: bullseye lxc network problem 
C :: mettre int dans string c % 
C :: Example of header file c 
C :: return multiple values using the call by reference 
C :: why return 0 is written at the code end? 
C :: C fgets() and puts() 
C :: how to write 2d array from bin file in c 
C :: Program optimization 
C :: nosql injection 
C :: c Write a program to reverse an array or string 
C :: filing in c 
Dart :: flutter validate email 
Dart :: flutter clear navigation stack 
Dart :: flutter textfield outlineinputborder 
Dart :: dart datetime difference 
Dart :: flutter launcher icon generate 
Dart :: How do you add a label (title text) to a Checkbox in Flutter? 
Dart :: send null icon flutter 
Dart :: clickable card flutter 
Dart :: flutter column vertical direction 
ADD CONTENT
Topic
Content
Source link
Name
9+4 =