Thursday 4 August 2016

Arrays Bubble sort

Sorting an Array using Bubble Sort

#include<stdio.h>
void main()
{
         int i, j, n, a[10], temp;
         printf("\nEnter the value of n:");
         scanf("%d", &n);

         printf("\nEnter array elements:");
         for(i=0;  i<n;  i++)
                   scanf("%d", &a[i]);

         for(i=0; i<n-1; i++)
        {
              for(j=0; j<n-1-i; j++)
              {
                    if(a[j+1]<a[j])
                    {
                             temp = a[j+1];
                             a[j+1] = a[j];
                             a[j] = temp;
                     }
                }
         }

          printf("\nBubble sort: array elements:");
          for(i=0;i<n;i++)
                   printf("%d ", a[i]);
 }

Output

Enter the value of n: 7
Enter array elements: 3 2 1 5 6 9 1

Bubble sort: array elements: 1 1 2 3 5 6 9

No comments:

Post a Comment