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

    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 }
  • 相关阅读:
    array and ram
    char as int
    pointer of 2d array and address
    Install SAP HANA EXPRESS on Google Cloud Platform
    Ubuntu remount hard drive
    Compile OpenSSL with Visual Studio 2019
    Install Jupyter notebook and tensorflow on Ubuntu 18.04
    Build OpenCV text(OCR) module on windows with Visual Studio 2019
    Reinstall VirtualBox 6.0 on Ubuntu 18.04
    Pitfall in std::vector<cv::Mat>
  • 原文地址:https://www.cnblogs.com/wangchaoyuan/p/5979017.html
Copyright © 2011-2022 走看看