MAP

GTU C PROGRAMS MATERIAL | BUBBLE SORT PROGRAM

C :

/* bubble.c */
#include <stdio.h>
#include <stdlib.h>
void bubble_sort(int array[], int size)
{
 int temp, i, j;
 for (i = 0; i < size; i++)
  for (j = 0; j < size; j++)
   if (array[i] < array[j])
   {
    temp = array[i];
    array[i] = array[j];
    array[j] = temp;
   }
}
void main(void)
{
 int values[30], i;
 printf("\n Unsorted list is as follows\n");
 for (i = 0; i < 10; i++)
 {
  values[i] = rand() % 100;
  printf(" %d", rand()%100);
 }
 bubble_sort(values, 10);
 printf("\n Sorted list is as follows\n");
 for (i = 0; i < 10; i++)
  printf("%d ", values[i]);
}

------------------------------------------------------------
C++

 // BUBBLE SORT
 # include<iostream.h>
 # include<conio.h>
     class bubble
      {
 private:
 public:
       void bubble_sort(int , int *); // prototype
       void display(int *, int);
      };
// definition of function
void bubble ::  bubble_sort(int n, int l[])
  {
      int limit = n - 1 ;
      int flag = 1 ;
   for(int j = 0 ; j< n - 1; j++)
   {
     for(int k = 0 ; k<  limit - j ; k++)
      {
        if(l[k] > l[k+1])
   {
    int  temp = l[k];
         l[k] = l[k+1];
         l[k+1] = temp ;
         flag = 0;
    }
        }
    if(flag)
       break ;
       else
        flag = 1;
     }
 }
      void bubble :: display(int list[], int number)
 {
   for( int i = 0 ; i < number ; i++)
   cout<<"  "<< list[i];
 }

 void main()
        {
  bubble sort;
  int number, key, list[200];
  clrscr();
  cout <<"Input the number of elements in the list:";
  cin >> number;
  cout <<"\n Number  of elements in the list is :"<<number;
  for(int i = 0 ; i < number; i++)
  {
  cout<<"\nInput the elements of the list : "<< i+1<<" : ";
  cin >> list[i];
  }
  cout<<"\n Entered list is as follows:\n";
  sort.display(list,number);
  sort.bubble_sort(number, list);
  cout<<"\n After sorting list is as  follows:\n";
  sort.display(list, number);
 }

0 comments:

Post a Comment

Twitter Delicious Facebook Digg Stumbleupon Favorites More