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

56 lines
777 B
C++
Raw Normal View History

2016-07-16 18:56:48 +08:00
//Bubble Sort
#include<iostream>
2018-12-22 13:01:52 +08:00
#include<vector>
2016-07-16 18:56:48 +08:00
using namespace std;
int main()
{
int n;
2019-02-09 15:55:12 +08:00
short swap_check=0;
2019-02-09 15:55:57 +08:00
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-02-09 15:55:57 +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
for(int i=0; i<n; i++)
2016-07-16 18:56:48 +08:00
{
2019-02-09 15:55:12 +08:00
swap_check=0;
for(int j=0; j<n-1-i; j++)
2016-07-16 18:56:48 +08:00
{
2018-12-22 13:01:52 +08:00
if(numbers[j]>numbers[j+1])
2016-07-16 18:56:48 +08:00
{
2019-02-09 15:55:12 +08:00
swap_check=1;
2018-12-22 13:01:52 +08:00
swap(numbers[j], numbers[j+1]);
2016-07-16 18:56:48 +08:00
}
}
2019-02-09 15:55:12 +08:00
if(swap_check == 0)
{
break;
}
2016-07-16 18:56:48 +08:00
}
2016-07-16 18:56:48 +08:00
//Output
cout<<"\nSorted Array : ";
2018-12-22 13:01:52 +08:00
for(int i=0; i<numbers.size(); i++)
2016-07-16 18:56:48 +08:00
{
2018-12-22 13:01:52 +08:00
if(i != numbers.size() -1)
{
cout << numbers[i] << ", ";
}else
{
cout << numbers[i] << endl;
}
2016-07-16 18:56:48 +08:00
}
2019-02-09 15:55:12 +08:00
return 0;
2016-07-16 18:56:48 +08:00
}