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

    排序思想:
    相当于一堆数字,一开始先取出2个数排序,2个数排好序之后,再从一堆数字里面取一个数排序,直到结束
    伪代码:
    INSERTION_SORT(A)
    for j = 2 to A.length
      key = A[j]
      //Insert A[j] into sorted sequence A[1...j-1].
      i = j - 1
      while i>0 and A[i]>key
        A[i+1] = A[j]
        i = i - 1

      A[i + 1] = key

    代码:

    import java.io.*;
    public class InsertionSort{
    public static void InsertionSort(int[] A){
      //从第二个元素开始循环
      for(int i=1;i<A.length;i++){
        //得到需要排序的数
        int key = A[i];
        //跟之前排好序的最大的元素开始比较,此时j为之前排好序的最大的元素的下标
        int j = i - 1;
        //循环比较,直到这个数>前一个数并且<后一个数
        while(j>=0&&A[j]>key){
        //比这个数大,则之前的数往后移
          A[j+1] = A[j];
          j = j - 1;
        }
        //把这个数放入数组中
        A[j + 1] = key;
      }
    }


    public static void main(String[] args) {
      int[] A = { 4, 6, 9, 10, 5, 3};
      InsertionSort(A);
      for(int a: A){
        System.out.print(a+" ");
      }
     }
    }

  • 相关阅读:
    python-序列化与反序列化(loads、load、dumps、dump)
    STM32命名
    批处理参考
    Delphi通过管道执行外部命令行程序(cmd)并获取返回结果
    ubuntu使用备忘
    ubuntu14.04中安装QuartusII9.1步骤
    删除选中数据
    DBGridEh基本操作
    sqlserver 字符串函数
    使用 Delphi Xe 的 TDictionary
  • 原文地址:https://www.cnblogs.com/yzdtofly/p/7241421.html
Copyright © 2011-2022 走看看