排序算法-插入排序

来源:互联网 发布:电话亭女孩 知乎 编辑:程序博客网 时间:2024/06/07 06:16

插入排序简介和jjava实现


插入排序的基本思想是:每步将一个待排序的纪录,按其关键码值的大小插入前面已经排序的文件中适当位置上,直到全部插入完为止。

插入排序的过程:



插入排序的java实现
package com.algorithm.sort;import com.algorithm.PrintUtils;public class InsertSort {public static int[] sort(int source[]) {for (int j=1; j < source.length; j++) {int key =source[j];int i=j-1;while(i>0&&source[i]>key){source[i+1]=source[i];i--;}source[i+1]=key;}return source;}public static Integer[] sort(Integer source[]) {for (Integer j=1; j < source.length; j++) {Integer key =source[j];Integer i=j-1;while(i>=0&&source[i]>key){source[i+1]=source[i];i--;}source[i+1]=key;}return source;}public static void main(String[] args) {Integer source[]={120,324,43,234253,2134,324,2765};Integer result[] =InsertSort.sort(source);new PrintUtils<Integer>().printArray(result);//System.out.println();}}

算法分析:时间复杂度o(N*N) 空间复杂度为O(1)



1 0