Need a project done?

C++ Programming Developer

Search This Blog

Bubble Sort C++

What is Bubble Sort or Bubble Sorting?

In Bubble Sort, we follow following steps:

•Sorting data
–Important computing application
–Virtually every organization must sort some data
•Massive amounts must be sorted

•Bubble sort (sinking sort)
–Several passes through the array
–Successive pairs of elements are compared
•If increasing order (or identical), no change
•If decreasing order, elements exchanged
–Repeat these steps for every element

•Example:
–Go left to right, and exchange elements as necessary
•One pass for each element
–Original:   3  4  2  7  6
–Pass 1:      3  2  4  6  7   (elements exchanged)
–Pass 2:      2  3  4  6  7
–Pass 3:      2  3  4  6  7   (no changes needed)
–Pass 4:      2  3  4  6  7
–Small elements "bubble" to the top (like 2 in this example)

•Swapping variables
int x = 3, y = 4;
y = x;
x = y;
•What happened?
–Both x and y are 3!
–Need a temporary variable

•Solution
int x = 3, y = 4, temp = 0;
temp = x;  // temp gets 3
x = y;     // x gets 4
y = temp;  // y gets 3


Bubble Sorting in C++:

#include<iostream>
using namespace std;


int main()
//Program for Bubble Sorting.
{
 const int array_size = 4;
 int x[array_size],  hold;

 for (int i = 0 ; i <= 3 ; i++ ) //Inititalizing four Numbers from user.
 cin>>x[i];

 cout<<"\nOriginal Numbers:\n"; //Printing Original Numbers.
  for ( i=0; i<=3 ; i++) //Printing
   cout<<x[i]<<"   ";


  //Bubble Sorting begins
 for (int passes = 0;  passes < array_size - 1;  passes++)
 {
  for (int j = 0;  j < array_size - passes - 1;  j++)
  {
   if (x[j] > x[j+1])
   {
    hold = x[j];
    x[j] = x[j+1];
    x[j+1]=hold;

   }
  }
 }  //Bubble Sorting finished

 cout<< "\nAscending Order:\n"; //Printing Numbers in Ascending order.

 for (i = 0; i<4 ; i++) //Printing
  cout<< x[i]<<"   ";
 cout<<endl<<endl;
 return 0;
}

2 comments:

  1. this only works 4 only 4 as the array size

    ReplyDelete
    Replies
    1. Because first line of code in main() is: const int array_size = 4; Change it to whatever size you want, or take int array_size as input from user and create array dynamically: int *x = new int [array_size];

      Delete

"Don't let anyone ever make you feel like you don't deserve what you want."