zoukankan      html  css  js  c++  java
  • 插入排序算法

    插入排序原理很简单,讲一组数据分成两组,我分别将其称为有序组与待插入组。每次从待插入组中取出一个元素,与有序组的元素进行比较,并找到合适的位置,将该元素插到有序组当中。就这样,每次插入一个元素,有序组增加,待插入组减少。直到待插入组元素个数为0。当然,插入过程中涉及到了元素的移动。

    为了排序方便,我们一般将数据第一个元素视为有序组,其他均为待插入组。

    下面以升序为例进行一次图解:

    插入排序算法的实现:

     1 public class InsertSort{
     2     
     3     public static <T extends Comparable<? super T>> void insertSort(T[] a){
     4         for(int p = 1; p < a.length; p++)
     5         {
     6             T tmp = a[p];//保存当前位置p的元素,其中[0,p-1]已经有序
     7             int j;
     8             for(j = p; j > 0 && tmp.compareTo(a[j-1]) < 0; j--)
     9             {
    10                     a[j] = a[j-1];//后移一位
    11             }
    12             a[j] = tmp;//插入到合适的位置
    13         }
    14     }
    15     
    16     //for test purpose
    17     public static void main(String[] args) {
    18         Integer[] arr = {34,8,64,51,32,21};
    19         insertSort(arr);
    20         for (Integer i : arr) {
    21             System.out.print(i + " ");
    22         }
    23     }
    24}
  • 相关阅读:
    centos git编译
    Unix/Linux小计
    centos gcc编译
    c++隐式转换(implicit conversion)
    通用c程序Makefile
    对弈的Python学习笔记
    LeetCode最长回文子串
    JDBC09 CLOB文本大对象
    JDBC08时间处理
    JDBC07 事务
  • 原文地址:https://www.cnblogs.com/guangzhou11/p/8779057.html
Copyright © 2011-2022 走看看