Bubble Sort with C Program

Bubble sort is a simple sorting algorithm that works by repeatedly stepping through the list to be sorted, comparing each pair of adjacent items and swapping them if they are in the wrong order. The pass through the list is repeated until no swaps are needed, which indicates that the list is sorted.
An example on bubble sort. Starting from the beginning of the list, compare every adjacent pair, swap their position if they are not in the right order (the latter one is smaller than the former one). After each iteration, one less element (the last one) is needed to be compared until there are no more elements left to be compared.
Definition and the animation courtesy: Wikipedia

Bubble Sort with C Program:



#include <stdio.h>

int main()
{
    int i, j,temp,n;
    int num[80];
    printf("How many elements (MAX: 80): ");
    scanf("%d",&n);
    
    printf("Enter %d integer numbers: ",n);
    for(i=0;i<n;i++)
        scanf("%d",&num[i]);
    for(i=0;i<n-1;i++){
        for(j=0;j<n-1-i;j++){
            if(num[j]>num[j+1]){ // To sort decreasing order use num[j]<num[j+1]
                temp = num[j+1];
                num[j+1] = num[j];
                num[j]  = temp;
            }
        }
    }
    printf("After sorting with Bubble Sort:\n");
    for(i=0;i<n;i++)
        printf("%d ",num[i]);
    return 0;
}

The above program will sort the given numbers into increasing order. If you want to sort the numbers decreasing order then just change the condition from num[j]>num[j+1] to num[j]<num[j+1].

0 comments :

Post a Comment

Spam comments will be deleted. :)

 
Loading...
TOP