zoukankan      html  css  js  c++  java
  • 选择法、冒泡、直插发排序

    View Code
    #include "stdafx.h"
    #include<iostream>
    #include<ctime>

    using namespace std;

    int _tmain(int argc, _TCHAR* argv[])
    {
        int a[20];
        srand((unsigned)time(0));//新版本的是64位,srand是32为
        for(int i=0;i<20;i++){
            a[i]=rand()%100+1;
        }
        //选择法排序(循环n-1次)思路:每一次找出适合的元素放在正确的位置上
        /*for(int i=0;i<19;i++){
          for(int j=i+1;j<20;j++){      
              if(a[i]>a[j]){
                  int temp=a[i];
                  a[i]=a[j];
                  a[j]=temp;
              }
          }
        }
    */
        
        //冒泡法排 思路:两两比较,大的下沉,小的上浮,每一轮都会找出最大的一个元素
        for(int i=1;i<20;i++){
            for(int j=0;j<20-i;j++){
                if(a[i]<a[j]){
                    int temp=a[i];
                    a[i]=a[j];
                    a[j]=temp;
                }
            }
        }
        //比如循环到i=5的时候
        
    //关键部分是j=0;j<i;j++这部分循环,循环过后 最大数已经放到a[j] 里面了




        
    //输出所有
        for(int i=1;i<21;i++){
            if(i%7==0)
                cout<<a[i-1]<<"\t"<<endl;
            else
                cout<<a[i-1]<<"\t";

        }
        
        int b;
        cin>>b;
        return 0;
    }

    直插发: 

    View Code
    #include "stdafx.h"
    #include<iostream>
    using namespace std;

    void insert_sort(int * lstNum, size_t nSize)
    {
        if (nSize < 2)
            return;
        int nTemp;
        size_t i = 1, a;
        while (i < nSize)
        {
            nTemp = lstNum[i];
            a = i - 1;
            while (lstNum[a] > nTemp && a >= 0// a >= 0 is very import!
            {
                lstNum[a + 1] = lstNum[a];
                a--;
            }
            lstNum[a + 1] = nTemp;
            i++;
        }
    }
    int _tmain(int argc, _TCHAR* argv[])
    {
        int a[]={4,5,1,3};
        insert_sort(a,4);
        for(int j=0;j<4;j++){
        cout<<a[j]<<endl;
        }

        return 0;
    }
  • 相关阅读:
    mybatis报错invalid types () or values ()解决方法
    windows下新安装的mysql修改root password问题
    2分钟在eclipse下使用SpringBoot搭建Spring MVC的WEB项目
    Windows 10 下mysql 安装后无法启动问题
    【Head-First设计模式】C#版-学习笔记-开篇及文章目录
    【博客美化】03.分享按钮
    【博客美化】02.公告栏显示个性化时间
    【博客美化】文章目录
    MySql字段类型及字节
    数据库设计原则
  • 原文地址:https://www.cnblogs.com/clc2008/p/2390780.html
Copyright © 2011-2022 走看看