Thursday, 17 March 2016

WAP to implement Bubble Sort

//WAP in C to take an array as an input and sort it using Bubble Sort Algorithm
#include<stdio.h>
#include<conio.h>

int main()
{
      int arr[50], num, i, j, temp = 0; // required variables
      clrscr(); // clearing the console screen 

      printf("Enter how many numbers you want: "); 
      scanf("%d", &num); // taking array length
      printf("\nEnter the %d elements:\n", num); 

     for (i = 0; i < num; i++)
     { 
       scanf("%d", &arr[i]); // taking array input 
     }

// sorting the array using temporary variable

     for (i = 0; i < num; i++)      
     { 
       for (j = i + 1; j < num; j++)
       { 
         if (arr[i] > arr[j])
         {
           temp = arr[i]; 
           arr[i] = arr[j]; 
           arr[j] = temp;
         }
       } 
     } 

// printing the sorted array
      printf("\n\n\n\t\tThe sorted array using Bubble sort is:\n"); 
      for (i = 0; i < num; i++) 
      { 
        printf("\n\t\t%d", arr[i]); 
      }
return 0;  
getch(); // for holding the console screen
}

No comments:

Post a Comment