36 lines
850 B
C++
36 lines
850 B
C++
#include <iostream>
|
|
#include <vector>
|
|
#include <algorithm>
|
|
|
|
using namespace std;
|
|
|
|
/*
|
|
* function : implement bubble sort
|
|
* param nums : the vector to be sorted
|
|
* param comp_count : count of comparisons
|
|
* param move_count : count of moves
|
|
* return : ---
|
|
*/
|
|
void BubbleSort(vector<int> &nums, long long &comp_count, long long &move_count)
|
|
{
|
|
bool swapped;
|
|
for (int i = 0; i < static_cast<int>(nums.size()) - 1; i++)
|
|
{
|
|
swapped = false;
|
|
for (int j = 0; j < static_cast<int>(nums.size()) - 1 - i; j++)
|
|
{
|
|
comp_count++;
|
|
if (nums[j] > nums[j + 1])
|
|
{
|
|
swap(nums[j], nums[j + 1]);
|
|
move_count += 3; // std::swap is 3 moves
|
|
swapped = true;
|
|
}
|
|
}
|
|
if (!swapped)
|
|
{
|
|
break;
|
|
}
|
|
}
|
|
}
|