排序算法:插入排序

来源:互联网 发布:c十十语言范磊视频教程 编辑:程序博客网 时间:2024/06/08 01:09

插入排序的算法思想为:从第二个元素开始,与它之前的元素比较,如果当前元素大于参与比较的元素,则交换两个元素的位置,另外一种表述为在当前元素之前通过搜索的方法,找到第一个比它小的元素m,将当前元素插入到m后面,搜索的方法可以采用二分法。


C++实现代码

#include <iostream>#include <vector>using namespace std;template<typename T>void InsertionSort(vector<T> &vec);int main(){int arr[10] = { 8, 3, 10, 49, 2, 6, 13, 5, 14, 7 };vector<int> vec(&arr[0], &arr[10]);InsertionSort(vec);return 0;}// Insertion Sort with double partition search algorithmtemplate<typename T>void InsertionSort(vector<T> &vec){int VSize = vec.size();if (VSize < 1)return;if (1 == VSize){cout << "Only one element in array: " << vec[0] << endl;return;}for (int vIdx = 1; vIdx < VSize; vIdx++){bool inserted = false;int left = 0;int right = vIdx - 1;int gIdx = 0;                  // the insert goal indexif (vec[vIdx] > vec[vIdx - 1])continue;if (vec[vIdx] < vec[0])gIdx = 0;else{while (!inserted){if (1 == right - left){gIdx = right;inserted = true;}else{if (vec[vIdx] > vec[(left + right) / 2])left = (left + right) / 2;elseright = (left + right) / 2;}}}for (int tIdx = vIdx - 1; tIdx >= gIdx; tIdx--){vec[tIdx] ^= vec[tIdx + 1];vec[tIdx + 1] ^= vec[tIdx];vec[tIdx] ^= vec[tIdx + 1];}}for (int vIdx = 0; vIdx < VSize; vIdx++){cout << "index " << vIdx << " value " << vec[vIdx] << endl;}return;}


0 0
原创粉丝点击