zoukankan      html  css  js  c++  java
  • 插入排序 C&&C++

    (blog主要用于展示算法流程)
    插入排序算法:通过对未排序的数据逐个插入合适的位置而完成排序工作
     
     
     
    流程:
    (1)先对数组前两个数据进行从小到大排序
    (2)将第三个数据与前两个数据比较,将第三个数据插入合适的位置
    (3)将第四个数据插入已排序好的前三个数据中
    (4)不断重复,直到把最后一个数据插入合适的位置
     
     
     1 #include<iostream>
     2 #include<cstdlib>
     3 #include<ctime>
     4 using namespace std;
     5 void InsertionSort(int a[],int len)
     6 {
     7     int t;
     8     for (int i = 0; i < len; i++)
     9     {
    10         t=a[i];
    11         int j=i-1;
    12         while (j>=0&&t<a[j])
    13         {
    14             a[j+1]=a[j];
    15             j--;
    16         }
    17         a[j+1]=t;
    18         cout<<"Sort result after"<<i+1<<"step:";     //输出每一步的排序结果
    19         for(int k=0;k<len;k++) cout<<a[k]<<" ";
    20         cout<<endl;
    21     }
    22 }
    23 int main()
    24 {
    25     int a[10];
    26     srand(time(NULL));
    27     cout<<"Array before sorting:"<<endl;
    28     for (int i = 0; i < 10; i++)                                 //采用随机数作为数组输入
    29     {
    30         a[i]=rand()/1000;
    31         cout<<a[i]<<" ";
    32     }
    33     cout<<endl;
    34     InsertionSort(a,10);
    35     cout<<"Array after sort:"<<endl;
    36     for (int i = 0; i < 10; i++) cout<<a[i]<<" ";
    37     cout<<endl;
    38     return 0;
    39     
    40 }
     
     
     
     
     
     
     
     
  • 相关阅读:
    Bzoj 3654 图样图森波 题解
    1.27号考试记录
    博弈论入门小结
    「考试总结」2020-11-18 爆零
    「补题」考试题泛做
    CSP2020 游记,总结与题解
    Luogu2827 「NOIP2016」 蚯蚓
    【学习笔记】四毛子算法
    「考试反思」2020-11-04 临行
    「考试反思」2020-10-31 警示
  • 原文地址:https://www.cnblogs.com/Arthas8086/p/11948832.html
Copyright © 2011-2022 走看看