Bubble sort in C

What is Bubble sort? Bubble sort is one of the basic and simple sorting techniques. Bubble sort is not advisable for huge amount of data. In today world, we may not be able to employ bubble sort technique because of the size of the data. But, learning a basic and easiest techniques will help us in improving our knowledge and will lay as foundation for further advanced techniques.

In this method, we sort the entire array by comparing each and every element with next element. If the next element is smaller than current element, then those two elements are swapped and if it is greater then left intact. For Bubble sort program in Java

The code below is self explanatory:

#include <stdio.h>
#include <conio.h>
void sort(int);

void main(){
    int size;

    printf("\n Enter size of the array: "); //Request for size of array
    scanf("%d",&size);
    sort(size); //Invoking sorting function with size as parameter

    getch();
};

void sort(int size){
    int data[size],i,j,order,swap;

    for(i=0;i< size; i++){
        printf("\n Enter data into the array: "); //Enter the data into the array
        scanf("%d",&data[i]);
    }

    printf("\n Enter for 1 for ascending order or 2 for descending order: "); // Ascending order or descending order
    scanf("%d",&order);

    if(order == 1){
            /*Ascending order*/
            for(i=0;i<size;i++){
                for(j=0;j<size-1;j++){
                    if(data[j] > data[j+1]){
                        swap      = data[j];
                        data[j]   = data[j+1];
                        data[j+1] = swap;
                    }
                }
            }
        }

        else {
            /*Descending order*/
            for(i=0;i<size;i++){
                for(j=0;j<size-1;j++){
                    if(data[j] < data[j+1]){
                        swap      = data[j];
                        data[j]   = data[j+1];
                        data[j+1] = swap;
                    }
                }
            }
        }

        printf("\n Sorted data is:\n"); //Display of final sorted data
        for(i=0;i<size;i++){
            printf("\t%d",data[i]);
        }
}

Output:
bubble

Download the Source Code

Advertisement

About Anuroop D

Very enthusiastic about technology and likes to share my knowledge through blogging. Has Bachelor's in Information Technology and currently pursuing my PhD in Computer Science.
This entry was posted in C and tagged , , , , , , , , , , . Bookmark the permalink.

1 Response to Bubble sort in C

  1. Pingback: Insertion Sort in C | Letusprogram

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s