首页 > 编程 > C++ > 正文

C++ 排序插入排序实例详解

2020-01-26 14:05:17
字体:
来源:转载
供稿:网友

排序――插入排序

插入排序的基本思想是每次将一个待排序的记录,按其关键字大小插入到前面已经排好序的子文件中的适当位置,直到全部记录插入完成为止。常见的插入排序有插入排序(Insertion Sort),希尔排序(Shell Sort),二叉查找树排序(Tree Sort),图书馆排序(Library Sort),Patience排序(Patience Sort)。

简单实例:

#include <iostream>using namespace std;void InsertSort( int k[], int n ){  int i, j,temp;    for( i=1; i < n;i++ )  {    if( k[i] < k[i-1] )    {      temp = k[i];            for( j=i-1; k[j] > temp;j-- ) //找位置并且向后推移       {        k[j+1] = k[j];      }            k[j+1] = temp;    }  }}int main(){  int i ,a[10] = {5,2,6,0,3,9,1,7,4,8};    InsertSort(a,10);    for( i=0; i < 10 ;i++ )  {    cout << a[i];  }    cout << endl;    return 0;}

感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表