InsertSort

  直接插入排序:

    思想:每趟将一个待排序的元素作为关键字,按照其关键字值的大小插入到已经排好的部分序列的适当位置,知道插入而完成。

    性能:

       时间复杂度:最坏:O(n^2),最好O(n),平均O(2^n);

       空间复杂度:O(1);

    代码:

 1 package com.wang.sort;
 2 /*
 3  * @tittle: insertsort
 4  * @author:wwwglin
 5  * @time:2016/04.18
 6  */
 7 public class InsertSort {
 8     public void insertSort(int[] nums) {
 9         int temp = 0;
10         for (int i = 1; i < nums.length; i++) {
11             temp = nums[i];
12             int j = i-1;
13             while (j >= 0 && temp < nums[j]){
14                 nums[j+1]=nums[j];
15                 j--;
16             }
17             nums[j+1] = temp;
18         }
19     }
20 
21     public static void main(String[] args) {
22         int[] nums = { 49, 38, 65, 97, 76, 13, 27, 49 };
23         System.out.println("排序前:");
24         for (int i : nums) {
25             System.out.print(i + ",");
26         }
27         new InsertSort().insertSort(nums);
28         System.out.println();
29         System.out.println("排序后:");        
30         for (int i : nums) {
31             System.out.print(i + ",");
32         }
33     }
34 }

 

posted @ 2016-04-18 14:04  wwwglin  阅读(210)  评论(0)    收藏  举报