TheAlgorithms-C-Plus-Plus/Sorting/Bubble Sort.cpp

57 lines
818 B
C++
Raw Normal View History

2016-07-16 18:56:48 +08:00
//Bubble Sort
2019-08-21 10:10:08 +08:00
#include <iostream>
#include <vector>
2016-07-16 18:56:48 +08:00
using namespace std;
int main()
{
int n;
2019-08-21 10:10:08 +08:00
short swap_check = 0;
cout << "Enter the amount of numbers to sort: ";
cin >> n;
2018-12-22 13:01:52 +08:00
vector<int> numbers;
cout << "Enter " << n << " numbers: ";
int num;
2019-08-21 10:10:08 +08:00
//Input
for (int i = 0; i < n; i++)
2016-07-16 18:56:48 +08:00
{
2018-12-22 13:01:52 +08:00
cin >> num;
numbers.push_back(num);
2016-07-16 18:56:48 +08:00
}
2016-07-16 18:56:48 +08:00
//Bubble Sorting
2019-08-21 10:10:08 +08:00
for (int i = 0; i < n; i++)
2016-07-16 18:56:48 +08:00
{
2019-08-21 10:10:08 +08:00
swap_check = 0;
for (int j = 0; j < n - 1 - i; j++)
2016-07-16 18:56:48 +08:00
{
2019-08-21 10:10:08 +08:00
if (numbers[j] > numbers[j + 1])
2016-07-16 18:56:48 +08:00
{
2019-08-21 10:10:08 +08:00
swap_check = 1;
swap(numbers[j], numbers[j + 1]);
2016-07-16 18:56:48 +08:00
}
}
2019-08-21 10:10:08 +08:00
if (swap_check == 0)
{
break;
}
2016-07-16 18:56:48 +08:00
}
2016-07-16 18:56:48 +08:00
//Output
2019-08-21 10:10:08 +08:00
cout << "\nSorted Array : ";
for (int i = 0; i < numbers.size(); i++)
2016-07-16 18:56:48 +08:00
{
2019-08-21 10:10:08 +08:00
if (i != numbers.size() - 1)
2018-12-22 13:01:52 +08:00
{
cout << numbers[i] << ", ";
2019-08-21 10:10:08 +08:00
}
else
2018-12-22 13:01:52 +08:00
{
cout << numbers[i] << endl;
}
2016-07-16 18:56:48 +08:00
}
2019-08-21 10:10:08 +08:00
return 0;
2016-07-16 18:56:48 +08:00
}