zoukankan      html  css  js  c++  java
  • 程序员需要掌握的排序算法之直接插入排序

    直接插入算法

    基本思想在要排序的一组数中,假设前面(n-1) [n>=2] 个数已经是排好顺序的,现在要把第n个数插到前面的有序数中,使得这n个数也是排好顺序的。如此反复循环,直到全部排好顺序。

    package sortalgorithm;
    
    public class StraightInsertionSort {
    	public void insertSort() {
    		int[] a = { 1, 3, 2, 4, 10, 7, 8, 9, 5, 6 };
    		int temp = 0;
    		for (int i = 1; i < a.length; i++) {
    			int j = i - 1;
    			temp = a[i];
    			for (; j >= 0 && temp < a[j]; j--) {
    				a[j + 1] = a[j];
    			}
    			a[j + 1] = temp;
    			System.out.println("第"+i+"次:");
    			for (int k = 0; k < a.length; k++) {
    				System.out.print(a[k] + " ");
    			}
    			System.out.println();
    		}
    		System.out.println("最终:");
    		for (int i = 0; i < a.length; i++) {
    			System.out.print(a[i] + " ");
    		}
    	}
    
    	public static void main(String[] args) {
    		StraightInsertionSort aa = new StraightInsertionSort();
    		aa.insertSort();
    	}
    }
    

      运行结果:

  • 相关阅读:
    A1035
    A1005
    A1073
    A1061
    A1058
    A1027
    A1019
    Java 操作临时文件创建与删除
    面试必会之HashMap源码分析
    springboot整合cxf框架启动报错
  • 原文地址:https://www.cnblogs.com/liucldq/p/8528711.html
Copyright © 2011-2022 走看看