//
// Created by Admin on 2018/4/26.
//
#ifndef ALGORITHM_INSERTSORT_H
#define ALGORITHM_INSERTSORT_H
#include <vector>
class InsertSort {
public:
InsertSort() = default;
virtual ~InsertSort() = default;
void solution(std::vector<int>& vec);
};
#endif //ALGORITHM_INSERTSORT_H
//
// Created by Admin on 2018/4/26.
//
#include "InsertSort.h"
#include <iostream>
void InsertSort::solution(std::vector<int> &vec) {
int j = 0,tmp = 0;
int n = vec.size();
for(int i = 1; i < n; i++) {
tmp = vec[i];//从待插入数组中取出一个。
j = i - 1;//i - 1 为有序数组中的最后一个。
while( j >= 0 && tmp < vec[j]) {//判断条件为 j >= 0 是边界条件,第二个为插入判断条件。
vec[j + 1] = vec[j];//若不是合适位置,有序数组向后移动。
j --;
}
vec[j + 1] = tmp;//找到合适位置将元素插入。
}
}
int main(int argc,char** argv)
{
std::vector<int> v = { 1,5,8,7,4,6};
InsertSort sort;
sort.solution(v);
for(auto& c : v){
std::cout << c <<" ";
}
std::cout << std::endl;
}