Skip to content

Instantly share code, notes, and snippets.

@taisyo7333
Last active October 22, 2016 14:19
Show Gist options
  • Save taisyo7333/241f65fb2826d411b7640b0d34de41c8 to your computer and use it in GitHub Desktop.
Save taisyo7333/241f65fb2826d411b7640b0d34de41c8 to your computer and use it in GitHub Desktop.
C++ : Bubble Sort
#include<vector>
#include<iostream>
#include<utility> // from C++11
std::vector<int> bubble_sort(const std::vector<int>& input)
{
std::vector<int> work(input);
for (int i = work.size() - 1; i >= 0; i--) {
for (int j = 0; j < i; j++) {
if (work[j] > work[j + 1]) {
std::swap(work[j], work[j + 1]);
}
}
}
return work;
}
std::vector<int> bubble_sort2(const std::vector<int>& input)
{
std::vector<int> work(input);
for (int i = 0; i < work.size() - 1; i++) {
for (int j = work.size() - 1; j > i; j--) {
if (work[j - 1] > work[j]) {
std::swap(work[j], work[j - 1]);
}
}
}
return work;
}
int main()
{
std::vector<int> input = {5,6,8,1,3,7,4,2};
for (auto v : input) {
std::cout << v << ",";
}
std::cout << std::endl;
auto result = bubblesort(input);
for (auto v : result) {
std::cout << v << ",";
}
std::cout << std::endl;
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment