插入排序(Insertion-Sort)
算法描述
依次比较元素,将元素依次往后移动,挪出一个合适的位置,然后将值放入其中。
具体实现
#include <iostream>
#include <vector>
using namespace std;
class Solution {
public:
//插入排序算法
void insertion_sort(vector<int>& vec) {
for (int i = 1; i < vec.size(); i++) {
int key = vec[i];
int j = i - 1;
while(j >= 0 && key < vec[j]) {
vec[j + 1] = vec[j];
j--;
}
vec[j + 1] = key;
}
}
};
int main() {
int arr[] = {1, 2, 3, 4, 1, 3, 4, 2, 2, 3};
vector<int> vec(arr, arr+10);
Solution* solution = new Solution();
solution->insertion_sort(vec);
for (int i = 0; i < vec.size(); i++) {
cout << vec[i] << " ";
}
cout << endl;
return 0;
}