插入排序算法(insertion-sort)

一、用途:

输入:n个数(a1,a2,...,an)

输出:输入序列的一个排列(即重新排序)<a1',a2',...,an'>,使得a1' <= a2' <= ...an'.

待排序的数成为关键字key.

Insertion-sort的参数是一个数组A[1,2,...,N],包含n个待排序的数.(在代码中,A中元素个数n用length[A]表示).输入的个数字是原地排序的(sorted in place),意即这些数字就是在数组A中进行重新排序的.在任何时刻,至多只有其中的常数个数字是存储在数组之外的.dang过程Insertion-sort执行完毕后,输入数组A中就包含了已经排好序的输出序列.

                  

Insertion-sort(A)

1. for j <--- 2 to length[A]

2.   do  key  <--- A[j]

3.     Insert A[j] into the sorted sequence A[1....j-1]

4.     i <--- j-1

5.     while i > 0 and A[i] > key

6.       do A[i+1]  <---  A[i]

7.       i <--- i-1

8.     A[i-1] <--- key

 1 package org.jacky.algorithm.insertion.sort;
 2 
 3 public class InsertionSort {
 4     private static final int[] arrays = { 5, 3, 4, 1, 2 };
 5 
 6     public static void main(String[] args) {
 7         InsertionSort insertionSort = new InsertionSort();
 8         insertionSort.printArray(arrays);
 9         insertionSort.executeSort(arrays);
10         insertionSort.printArray(arrays);
11     }
12 
13     public void executeSort(int[] originalArray) {
14         if (originalArray == null || originalArray.length < 2) {
15             return;
16         }
17         for (int i = 1; i < originalArray.length; i++) {
18             int currentValue = originalArray[i];
19             int position = i;
20             for (int j = i - 1; j >= 0; j--) {
21                 if (originalArray[j] > currentValue) {
22                     originalArray[j + 1] = originalArray[j];
23                     position -= 1;
24                 } else {
25                     break;
26                 }
27             }
28             originalArray[position] = currentValue;
29         }
30     }
31 
32     public void printArray(int[] array) {
33         System.out.print("{");
34         for (int i = 0; i < array.length; i++) {
35             System.out.print(array[i]);
36             if (i < array.length - 1) {
37                 System.out.print(", ");
38             }
39         }
40         System.out.println("}");
41     }
42 }
View Code

 

转载于:https://www.cnblogs.com/Jacky312/p/5209191.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值