• 直接插入排序


    思想:(见图)


    方法一:

    直接上代码:

    void InsertSort(int *a,int size)
    {
    	assert(a);
    	int i, j, tmp;
    	for (i = 0; i < size-1; ++i)
    	{
    		tmp = a[i + 1];
    		for (j = i; j >= 0; --j)   //在有序序列中插入后来数
    		{
    			if (a[j] > tmp)
    			{
    				a[j+1] = a[j];
    			}
    			else
    			{
    				break;
    			}
    		}
    		a[j+1] = tmp;//原来时上边的J最后又减了一个
    	}
    }
    方法二:

    其实是一个有问题的程序,因为出现数组下标是负数了,源于功能能实现,所以摆放于此

    //很可笑的一个问题
    void InsertSort(int *a,int size)
    {
    	assert(a);
    	int i, j, tmp;
    	for (i = 0; i < size-1; ++i)
    	{
    		tmp = a[i + 1];
    		for (j = i; j >= -1; --j)
    		{
    			if (a[j] > tmp)          //[j] j尽然成负数了
    			{
    				a[j+1] = a[j];
    			}
    			else
    			{
    				a[j + 1] = tmp;
    				break;
    			}
    			
    		}
    	}
    }
    方法三:

    //下面就是对的
    void InsertSort(int a[], int len)
    {
    	int i, j, temp;
    	for (i = 1; i<len; i++)
    	{
    		if (a[i]<a[i - 1])
    		{
    			temp = a[i];
    			for (j = i - 1; a[j]>temp; j--)
    				a[j + 1] = a[j];
    			a[j + 1] = temp;
    		}
    	}
    }

    方法四:

    end为有序序列最后一个元素下标

    void InsertSort(int *a, int size)
    {
    	assert(a);
    	for (int i = 1; i < size; ++i)
    	{
    		int index = i;
    		int tmp = a[index];
    		int end = index - 1;
    		while (end >= 0 && tmp < a[end])
    		{
    			a[end + 1] = a[end];
    			--end;
    		}
    		a[end + 1] = tmp; //这里end加一是因为上边多减得一个
    	}
    }




  • 相关阅读:
    用 ArcMap 发布 ArcGIS Server Feature Server Feature Access 服务 SQL Server版
    ArcGIS Server Manager 重置密码
    接口自动化过程中遇到的问题?
    接口自动化的闭环?
    每天有80亿的文件需要存储,你会怎么设计存储和检索?
    数据库之索引
    java之高并发锁
    测试环境搭建
    shell基本语法
    RPC和HTTP
  • 原文地址:https://www.cnblogs.com/melons/p/5791867.html
Copyright © 2020-2023  润新知