32 lines
743 B
C++
32 lines
743 B
C++
|
/**
|
|||
|
* 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;
|
|||
|
}
|