cpp-algo-cases/chapter_sorting/insertion_sort.cpp

32 lines
743 B
C++
Raw Normal View History

2024-02-20 16:13:23 +08:00
/**
* File: insertion_sort.cpp
* Created Time: 2022-11-25
* Author: krahets (krahets@163.com)
*/
#include "../utils/common.hpp"
/* <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> */
void insertionSort(vector<int> &nums) {
// <20><>ѭ<EFBFBD><D1AD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>Ԫ<EFBFBD><D4AA><EFBFBD><EFBFBD><EFBFBD><EFBFBD>Ϊ 1, 2, ..., n
for (int i = 1; i < nums.size(); i++) {
int base = nums[i], j = i - 1;
// <20><>ѭ<EFBFBD><D1AD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> base <20><><EFBFBD><EFBFBD><EBB5BD><EFBFBD><EFBFBD><EFBFBD>򲿷ֵ<F2B2BFB7><D6B5><EFBFBD>ȷλ<C8B7><CEBB>
while (j >= 0 && nums[j] > base) {
nums[j + 1] = nums[j]; // <20><> nums[j] <20><><EFBFBD><EFBFBD><EFBFBD>ƶ<EFBFBD>һλ
j--;
}
nums[j + 1] = base; // <20><> base <20><>ֵ<EFBFBD><D6B5><EFBFBD><EFBFBD>ȷλ<C8B7><CEBB>
}
}
/* Driver Code */
int main() {
vector<int> nums = {4, 1, 3, 1, 5, 2};
insertionSort(nums);
cout << "<EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>ɺ<EFBFBD> nums = ";
printVector(nums);
return 0;
}