57 lines
1.4 KiB
C++
57 lines
1.4 KiB
C++
|
//
|
||
|
// Created by Marcus Vinícius de Carvalho.
|
||
|
//
|
||
|
|
||
|
#include <iostream>
|
||
|
using namespace std;
|
||
|
|
||
|
class BubbleSort {
|
||
|
private:
|
||
|
//Optional, because member attributes are private by default in C++
|
||
|
int _size;
|
||
|
int *_numArray;
|
||
|
|
||
|
public:
|
||
|
BubbleSort(int nums[], int size) {
|
||
|
_size = size;
|
||
|
_numArray = nums;
|
||
|
}
|
||
|
|
||
|
~BubbleSort() {
|
||
|
// This is a destructor. It was introduced in C++ 20. If you are programming on an older version, you will
|
||
|
// have to manually clean the memory
|
||
|
}
|
||
|
|
||
|
void sort() {
|
||
|
int t;
|
||
|
for (int i = _size - 2; i >= 0; i--) {
|
||
|
for (int j = 0; j <= i; j++) {
|
||
|
if (_numArray[j] > _numArray[j + 1]) {
|
||
|
t = _numArray[j];
|
||
|
_numArray[j] = _numArray[j + 1];
|
||
|
_numArray[j + 1] = t;
|
||
|
}
|
||
|
}
|
||
|
}
|
||
|
}
|
||
|
};
|
||
|
|
||
|
int main() {
|
||
|
int a[100], n, i;
|
||
|
|
||
|
std::cout << "Enter number of Integers elements to be sorted: ";
|
||
|
std::cin >> n;
|
||
|
|
||
|
for (i = 0; i < n; i++) {
|
||
|
std::cout << "Enter integer value for elements no." << i + 1 << ": ";
|
||
|
std::cin >> a[i];
|
||
|
}
|
||
|
|
||
|
BubbleSort b(a, n);
|
||
|
b.sort();
|
||
|
|
||
|
std::cout << "\nFinally sorted array is: ";
|
||
|
for (i = 0; i < n; i++) {
|
||
|
std::cout << a[i] << " ";
|
||
|
}
|
||
|
}
|