In this example, you will learn to implement balloon sort algorithm in c++. The balloon sort is similar to the bubble sort, in that it compares elements of the array and swaps those that are not in their proper positions. The difference between these two sorts is the manner in which they compare the elements.
The balloon sort compares the first element with each following element of the array, making any necessary swaps.When the first pass through the array is complete, the balloon sort then takes the second element and compares it with each following element of the array swapping elements that are out of order. This sorting process continues until the entire array is ordered.
C++
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 |
#include <iostream> using namespace std; int main() { int num,N[10],x,y,z,temp; cout<<"Enter the size of an element: "; cin>>num; //accept input cout<<"Enter the "<<num<<" elements:"<<endl; for(x = 0; x < num; x++) { cin>>N[x]; //accept array element till n } //logic to sort array using Ballon sort for(x = 0; x < num; x++) { for(y = 0; y < num - x; y++) { if(N[x] > N[x + y]) { temp = N[x]; N[x] = N[x + y]; N[x + y] = temp; } } //print sorted array step by step cout<<"Step "<<x + 1<<": "; for(z = 0; z < num; z++) { cout<<" "<<N[z]; } cout<<"\n"; } //exit status return 0; } |
When you run the program, the output will be following:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
Enter the size of an element: 5 Enter the 5 elements: 12 8 3 19 2 Step 1: 2 12 8 19 3 Step 2: 2 3 12 19 8 Step 3: 2 3 8 19 12 Step 4: 2 3 8 12 19 Step 5: 2 3 8 12 19 |