• 插入排序 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 }
     
     
     
     
     
     
     
     
  • 相关阅读:
    第十二周作业
    第11周学习总结
    第十周学习总结(五一作业)
    第九周作业
    第八周作业
    第七周作业
    PAT1049、1048、1047
    例题3-5,例题4-2,例题4-3
    PAT甲级真题打卡:1002. A+B for Polynomials
    PAT甲级真题打卡:1001.A+B Format
  • 原文地址:https://www.cnblogs.com/Arthas8086/p/11948832.html
Copyright © 2020-2023  润新知