• 插入排序


    1、插入排序

      对于给定的一组记录,初始时假设第一个记录自成一个有序序列,其余记录为无序序列,接着从第二个记录开始,按照记录的大小依次将当前处理的记录插入到其之前的有序序列中,直至最后一个记录插入到有序序列中为止。

    2、代码实现

     1 package com.wcy.sort;
     2 
     3 /**
     4  * 时间:2016年10月19日
     5  * 题目:插入排序
     6  * 题目描述:对于给定的一组记录,初始时假设第一个记录自成一个有序序列,其余记录为无序序列,接着从第二个记录开始,按照记录的大小依次将当前处理的记录插入
     7  * 到其之前的有序序列中,直至最后一个记录插入到有序序列中为止。
     8  */
     9 public class InsertSortTest {
    10 
    11     /**
    12      * 直接插入排序
    13      * @param arr 待排序的数组
    14      * @return 排序之后的数组
    15      */
    16     public static int[] insertSort(int[] arr){
    17         for (int i = 1; i < arr.length; i++) {
    18             if (arr[i] < arr[i-1]) {
    19                 int temp = arr[i];
    20                 arr[i] = arr[i-1];
    21                 int j = i-2;
    22                 // 这里的j>=0必须放在temp<arr[j]之前,不然运行的时候会出数组范围。
    23                 for (; j >= 0&&temp < arr[j]; j--) {
    24                     arr[j+1] = arr[j];
    25                 }
    26                 arr[j+1] = temp;
    27             }
    28         }
    29         
    30         return arr;
    31     }
    32     
    33     /**
    34      * 打印数组函数
    35      * @param arr 待打印的数组
    36      */
    37     public static void showArray(int[] arr){
    38         System.out.print("[");
    39         for (int i = 0; i < arr.length; i++) {
    40             if (i == arr.length-1) {
    41                 System.out.print(arr[i]);
    42             }else {
    43                 System.out.print(arr[i] + ",");
    44             }
    45         }
    46         System.out.println("]");
    47     }
    48     
    49     /**
    50      * 用户页面测试
    51      * @param args
    52      */
    53     public static void main(String[] args) {
    54         int[] arr = {49,38,65,97,76,13,27,49};
    55         int[] arrResult = insertSort(arr);
    56         showArray(arrResult);
    57     }
    58 }
  • 相关阅读:
    成功给家长们举办了supermemo软件安装与使用的培训
    抓到两只IE8的虫子
    域名保护期是咋回事
    IE8开发人员工具,让web开发的客户端调试畅通无阻
    (转)网站成功的法则
    谢文的社区观
    玩《征途》感受——这么多年白玩游戏了 (zt)
    社区运营 VS 征途(转)
    SQLite多线程写锁文件解决方案
    sqlite和sql server语法上的一些区别
  • 原文地址:https://www.cnblogs.com/wangchaoyuan/p/5979017.html
Copyright © 2020-2023  润新知