zoukankan      html  css  js  c++  java
  • 插入排序(二)

    /**
     * 
     * @author Administrator
     * 插入排序原理:对于给定的一组记录,初始时假设第一个记录自成一个有序序列,其余记录为无序序列;
     * 接着从第二个记录开始,按照记录的大小依次将当前处理的记录插入到其之前的有序序列中,
     * 直至最后一个记录插入到有序序列中为止;
     *从原数组第2个元素开始,遍历数组,依次把遍历到的元素按照一定的顺序插入到当前元素的小数组中(自己总结)
     *排序过程是一个挖坑填坑的过程
     */
    
    public class InsertSort {
    	public static void printArray(int a[]){
    		for(int i=0;i<a.length;i++)
    			System.out.print(a[i]);
    	}
    
    	public static void insertSort(int a[]){
    		int n = a.length;
    		int temp =0;
    		for(int i=1;i<n;i++){
    			int j=i;
    			temp = a[j];
    			while(j>=1&&a[j-1]>temp){	//原子数组中的元素后移,注意边界条件。这是一个挖坑的过程
    				a[j] = a[j-1];
    				j--;
    			}
    			a[j]=temp;	//填坑
    		}
    			
    	}
    	public static void main(String[] args) {
    		// TODO Auto-generated method stub
    		int a[] ={5,4,3,2,1};
    		insertSort(a);
    		printArray(a);
    	}
    
    }
    

    运行结果:

    12345

  • 相关阅读:
    vuejs 实战 双向数据绑定
    ubuntu16安装cuda,cudnn,gpu版opencv
    ubuntu编译安装nginx并且配置流服务器
    安装使用mongodb
    c++ 编译安装ffmpeg
    apache2 日志文件太大的解决方案
    sql注入
    制作自己的电子词典
    python传递可变参数
    工厂模式
  • 原文地址:https://www.cnblogs.com/lixuwu/p/5676175.html
Copyright © 2011-2022 走看看