zoukankan      html  css  js  c++  java
  • 直接插入排序

    和选择排序一样,当前索引左边的所有元素都是有序的,但它们的最终位置还不确定,为了给更小的元素腾出空间,它们可能会被移动。当索引到达数组的右端时,数组排序就完成了。

    和选择排序不同的是,插入排序所需要的时间取决于输入中元素的初始顺序。对一个很大且其中的很多元素已经有序的数组会比无序数组或逆序数组排序要快的多。

    JavaScript

    function insertSort(ary) {
        var i, j, len = ary.length;
        var temp;
        
        for(i=1; i<len; i++) {
            temp = ary[i];
            for(j=i; j>0 && temp<ary[j-1]; j--) {
                ary[j] = ary[j-1];
            }
            ary[j] = temp;
        }
        
        return ary;
    }
    var ary = [5,4,3,2,1];
    console.log(insertSort(ary));
    

     

    Java

    public class Test {
    
    	public static void insertSort(int[] ary){
    		int i, j, temp;
    		int len = ary.length;
    		
    		for(i=1; i<len; i++) {
    			temp = ary[i];
    			for(j=i; j>0 && temp<ary[j-1]; j--) {
    				ary[j] = ary[j-1];
    			}
    			ary[j] = temp;
    		}
    	}
    	public static void main(String[] args) {
    		int[] ary = {5,4,3,2,1};
    		Test.insertSort(ary);
    		for(int it : ary) {
    			System.out.println(it);
    		}
    
    	}	
    }
    

      

    C

    #include <stdio.h>
    
    void insertSort(int ary[], int len) {
    	int i, j, temp;
    	for(i=1; i<len; i++) {
    		temp = ary[i];
    		for(j=i; j>0 && temp<ary[j-1]; j--) {
    			ary[j] = ary[j-1];
    		}
    		ary[j] = temp;
    	}
    }
    
    main() {
    	int i;
    	int ary[]  = {5,4,3,2,1};
    	insertSort(ary, 5);
    	for(i=0; i<5; i++) {
    		printf("%d", ary[i]);
    	}
    	
    }
    

      

      

  • 相关阅读:
    ubuntu卸载vsftpd出错
    Eclipse: the import java.util cannot be resolved
    C# webBrowser 获取元素class属性值
    获取 user-agents
    Python获取当前年月日
    使用pip安装Scrapy出错
    使用pip安装Scrapy出错
    VMware全屏时, 隐藏上方工具栏横条
    HDFS 常用命令
    简单的java Hadoop MapReduce程序(计算平均成绩)从打包到提交及运行
  • 原文地址:https://www.cnblogs.com/snandy/p/2205783.html
Copyright © 2011-2022 走看看