Files
algo2025/sort_closet/code-sorting/InsertSort.cpp
2025-12-18 16:00:22 +08:00

34 lines
721 B
C++

#include <iostream>
#include <vector>
#include <algorithm>
#include <ctime>
#include <cstdlib>
#include <stack>
#include <string>
#include <cstring>
using namespace std;
/*
* function : implement insert sort
* param nums : the vector to be sorted
* param comp_count : count of comparisons
* param move_count : count of moves
* return : ---
*/
void InsertSort(vector<int> &nums, long long &comp_count, long long &move_count)
{
for (int i = 1; i < static_cast<int>(nums.size()); i++)
{
int key = nums[i];
int j = i - 1;
while (j >= 0 && (comp_count++, nums[j] > key))
{
nums[j + 1] = nums[j];
move_count++;
j--;
}
nums[j + 1] = key;
move_count++;
}
}