Bubble Sort
The following C++ code will explains the implementation of Bubble sort and sort the user input numbers in descending order.The following implementation is in object oriented using the BubbleSort class and bs object. Actual logic of Bubble sort is in the function of BSort().
In BubbleSort.h
#include <iostream>
using namespace std;
class BubbleSort
{
public:
int arr[10];
public:
void BSort(int *arr)
{
for (int i = 0; i <= 9; ++i)
{
for (int j = i+1; j <= 9; ++j)
{
if (arr[i] > arr[j]) //Descending (small to big)
{
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
}
}
};
In main.cpp
#include "BubbleSort.h"
int main()
{
BubbleSort bs;
for (int i = 0; i <= 9; ++i)
{
cout << "Enter values in 1st array : " << i+1 << " of 10: ";
cin >> bs.arr[i];
}
bs.BSort(bs.arr);
cout << "\n\nAfter Bubble Sort input numbers are\n";
for (int i = 0; i <= 9; ++i)
{
cout << bs.arr[i] << "\t";
}
return 0;
}
Feel free to comment with your questions and suggestions regarding the post content...!
No comments:
Post a Comment
Your valuable comments are appreciated...!