[C++] 插入排序法 (Insertion sort)

来源:互联网 发布:python字符串截取函数 编辑:程序博客网 时间:2024/05/16 19:36

实现过程:


假设现有一系列顺序未排序数字(顺序由左至右)。

1. 首先,标记第一个数字为已排序

2. 针对其余未排序数字,提取出其中第一个数字

3. 对于所有已排序数字,首次呼叫此步骤,设置其中最后一个已排序数字索引为当前索引。
    其余次呼叫此步骤时,则当前索引设置为前一个数字(左方数字)的索引;若当前索引无法指向具体数字时,则跳至步骤6

4. 若 当前索引指向之已排序数字 > 提取出的数字,则当前索引+1的索引位置指向之值设置为当前索引指向之已排序数字
    否则跳至步骤6

5. 重复步骤3

6. 将提取出的数字插入当前索引+1的索引位置,设置为已排序。

7. 重复步骤2



具体过程如以下图示:



















...

.....

..............

...........................

...........................................


中间省略多个步骤
直接跳到排序过程最后收尾












实现代码:


#include <iostream>#include <windows.h>using namespace std;#define LENGTH_ARR 10template <typename T>void PrintArr(T* arr, int length){for(int i=0;i<length;i++)cout<<arr[i]<<" ";}template <typename T>void InsertionSort(T* arr, int length){int lastSortedIdx=0;// mark first element as sortedint extractedElement=-1;int currentSortedIdx=0;for(int unsortedIdx=lastSortedIdx+1 ; unsortedIdx < length ; unsortedIdx++, lastSortedIdx++) // for each unsorted element{extractedElement=arr[unsortedIdx]; // 'extract' the elementfor(currentSortedIdx=lastSortedIdx;currentSortedIdx>=0 ;currentSortedIdx--) // for i = lastSortedIndex to 0{if(arr[currentSortedIdx] > extractedElement) // if currentSortedElement > extractedElement// (this condition can move to for loop condition, and else is not nessecary)arr[currentSortedIdx+1]=arr[currentSortedIdx]; // move sorted element to the right by 1else{break;}}arr[currentSortedIdx+1]=extractedElement; // else: insert extracted elementprintf("Step %d: ", unsortedIdx);PrintArr(arr, LENGTH_ARR);printf("\n");}}int main(){int arr[LENGTH_ARR]={3,44,38,5,47,15,36,26,27,2};printf("Before: ");PrintArr(arr, LENGTH_ARR);printf("\n");InsertionSort(arr, LENGTH_ARR);printf("Final: ");PrintArr(arr, LENGTH_ARR);printf("\n");system("pause");return 0;}



0 0
原创粉丝点击