Friday, October 7, 2016

Bubble sort algorithm implementation.

#include<stdio.h>
int main()
{
     int i, j, n, temp, data[10];
     printf("Enter total numbers to be sorted:");
     scanf("%d",&n);
     //This program will be able to sort max 10 numbers.
    
     for(i=0; i<n; i++)
     {
           printf("Enter data[%d]:",i);
           scanf("%d",&data[i]);
     }
     printf("Unsorted data:");
     for(i=0; i<n; i++)
           printf("%d, ", data[i]);
    
     for(i=0; i<n; i++)
     {
           for(j=0; j<n-i-1; j++)
           {
                if(data[j] > data[j+1])
                {
                     temp = data[j];
                     data[j] = data[j+1];
                     data[j+1] = temp;
                }
                    
           }
     }
    
     printf("\nSorted data:");
     for(i=0; i<n; i++)
           printf("%d, ", data[i]);
     return 0;
}



Output of the program:

Enter total numbers to be sorted:5
Enter data[0]:1
Enter data[1]:3
Enter data[2]:2
Enter data[3]:4
Enter data[4]:5
Unsorted data:1, 3, 2, 4, 5,
Sorted data:1, 2, 3, 4, 5,


No comments:

Post a Comment