cpp-algo-cases/chapter_sorting/bubble_sort.cpp

57 lines
1.5 KiB
C++
Raw Normal View History

2024-02-20 16:13:23 +08:00
/**
* File: bubble_sort.cpp
* Created Time: 2022-11-25
* Author: krahets (krahets@163.com)
*/
#include "../utils/common.hpp"
/* ð<><C3B0><EFBFBD><EFBFBD><EFBFBD><EFBFBD> */
void bubbleSort(vector<int> &nums) {
// <20><>ѭ<EFBFBD><D1AD><EFBFBD><EFBFBD>δ<EFBFBD><CEB4><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>Ϊ [0, i]
for (int i = nums.size() - 1; i > 0; i--) {
// <20><>ѭ<EFBFBD><D1AD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>δ<EFBFBD><CEB4><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> [0, i] <20>е<EFBFBD><D0B5><EFBFBD><EFBFBD><EFBFBD>Ԫ<EFBFBD>ؽ<EFBFBD><D8BD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>Ҷ<EFBFBD>
for (int j = 0; j < i; j++) {
if (nums[j] > nums[j + 1]) {
// <20><><EFBFBD><EFBFBD> nums[j] <20><> nums[j + 1]
// <20><><EFBFBD><EFBFBD>ʹ<EFBFBD><CAB9><EFBFBD><EFBFBD> std::swap() <20><><EFBFBD><EFBFBD>
swap(nums[j], nums[j + 1]);
}
}
}
}
/* ð<><C3B0><EFBFBD><EFBFBD><EFBFBD>򣨱<EFBFBD>־<EFBFBD>Ż<EFBFBD><C5BB><EFBFBD>*/
void bubbleSortWithFlag(vector<int> &nums) {
// <20><>ѭ<EFBFBD><D1AD><EFBFBD><EFBFBD>δ<EFBFBD><CEB4><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>Ϊ [0, i]
for (int i = nums.size() - 1; i > 0; i--) {
bool flag = false; // <20><>ʼ<EFBFBD><CABC><EFBFBD><EFBFBD>־λ
// <20><>ѭ<EFBFBD><D1AD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>δ<EFBFBD><CEB4><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> [0, i] <20>е<EFBFBD><D0B5><EFBFBD><EFBFBD><EFBFBD>Ԫ<EFBFBD>ؽ<EFBFBD><D8BD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>Ҷ<EFBFBD>
for (int j = 0; j < i; j++) {
if (nums[j] > nums[j + 1]) {
// <20><><EFBFBD><EFBFBD> nums[j] <20><> nums[j + 1]
// <20><><EFBFBD><EFBFBD>ʹ<EFBFBD><CAB9><EFBFBD><EFBFBD> std::swap() <20><><EFBFBD><EFBFBD>
swap(nums[j], nums[j + 1]);
flag = true; // <20><>¼<EFBFBD><C2BC><EFBFBD><EFBFBD>Ԫ<EFBFBD><D4AA>
}
}
if (!flag)
break; // <20><><EFBFBD>֡<EFBFBD>ð<EFBFBD>ݡ<EFBFBD>δ<EFBFBD><CEB4><EFBFBD><EFBFBD><EFBFBD>κ<EFBFBD>Ԫ<EFBFBD>أ<EFBFBD>ֱ<EFBFBD><D6B1><EFBFBD><EFBFBD><EFBFBD><EFBFBD>
}
}
/* Driver Code */
int main() {
vector<int> nums = {4, 1, 3, 1, 5, 2};
bubbleSort(nums);
cout << "ð<EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>ɺ<EFBFBD> nums = ";
printVector(nums);
vector<int> nums1 = {4, 1, 3, 1, 5, 2};
bubbleSortWithFlag(nums1);
cout << "ð<EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>ɺ<EFBFBD> nums1 = ";
printVector(nums1);
return 0;
}