/*********************************************  
---------------------  
BUBBLE SORT Algorithm  
---------------------  
Bubble.Sort(Data,N)  
1. Repeat step 2 & 3 for i =  0 to N - 2  
2. for j = 0 to j < N - i  
3. if Data[j] < Data[j + 1]  
 swap Data[j] and Data[j + 1]  
4. Return  
**********************************************/  
  
#include "iostream.h"
#include "conio.h"  
  
void swap(int &a,int &b)  
{  
 int temp = a;  
 a = b;  
 b = temp;  
}  
  
int main()  
{  
 int num[50],n;  
 cout << "How many numbers? ";  
 cin >> n;  
 cout << "\nEnter " << n << " Numbers\n";  
 for(int i = 0;i < n;i++)  
  cin >> num[i];  
  
 for(int i = 0;i < n - 2;i++) //outer loop from First to Second Last  
  for(int j = 0;j < n - i;j++) //inner loop from First to n - i  
   if(num[j] > num[j+1]) //if current number is greater than next number,  
     swap(num[j],num[j+1]); //swap two numbres  
  
 /*  
  or,  
 for(int i = 0;i < n - 2;i++) //outer loop from First to Second Last  
  for(int j = n - 1;j > i;j--) //inner loop from last to greater than i  
   if(num[j] < num[j - 1]) //if current number is less than next number,  
    swap(num[j],num[j - 1]); //swap two numbers  
 */  
  
 //Print Output  
 cout << endl << endl;  
 for(int i = 0;i < n;i++)  
  cout << num[i] << ' ';  
  
 getch();  
 return 0;  
}  
OUTPUT
How many numbers? 10
Enter 10 Numbers   
25 65 47 88 64 10 -98 0 35 6 
-98 0 6 10 25 35 47 64 65 88
Download Original File
Bubble.cpp 
 
No comments:
Post a Comment