Bubble Sort - C Program


#include<stdio.h>
/* Logic : Do the following thing until the list is sorted
            (i) Compare two adjacent elements and check if they are in correct order(that is second one has
                to be greater than the first).
            (ii) Swap them if they are not in correct order.
 */

void BubbleSort(int *array,int number_of_elements)
{
       
int iter, temp, swapped;
       
do
       
{
                swapped
= 0; /* If no element is swapped array is sorted */
               
/* In the following loop compare every pair of adjacent elements and check
                   if they are in correct order */

               
for(iter = 1; iter < number_of_elements; iter++)
               
{
                       
if(array[iter-1] > array[iter])
                       
{
                                temp
= array[iter-1];
                                array
[iter-1] = array[iter];
                                array
[iter] = temp;
                                swapped
= 1;
                       
}
               
}

       
}while(swapped);
}
int main()
{
       
int number_of_elements;
        scanf
("%d",&number_of_elements);
       
int array[number_of_elements];
       
int iter;
       
for(iter = 0;iter < number_of_elements;iter++)
       
{
                scanf
("%d",&array[iter]);
       
}
       
/* Calling this functions sorts the array */
       
BubbleSort(array,number_of_elements);
       
for(iter = 0;iter < number_of_elements;iter++)
       
{
                printf
("%d ",array[iter]);
       
}
        printf
("\n");
       
return 0;

}
Comments