码迷,mamicode.com
首页 > 编程语言 > 详细

插入排序

时间:2016-10-20 00:27:32      阅读:128      评论:0      收藏:0      [点我收藏+]

标签:

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 }

 

插入排序

标签:

原文地址:http://www.cnblogs.com/wangchaoyuan/p/5979017.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!