插入排序(java实现)

来源:互联网 发布:什么是淘宝钻石买家 编辑:程序博客网 时间:2024/05/25 12:21

1. 定义:

有一个已经有序的数据序列,要求在这个已经排好的数据序列中插入一个数,但要求插入后此数据序列仍然有序,这个时候就要用到一种新的排序方法——插入排序法,插入排序的基本操作就是将一个数据插入到已经排好序的有序数据中,从而得到一个新的、个数加一的有序数据,算法适用于少量数据的排序,时间复杂度为O(n^2)。是稳定的排序方法。插入算法把要排序的数组分成两部分:第一部分包含了这个数组的所有元素,但将最后一个元素除外(让数组多一个空间才有插入的位置),而第二部分就只包含这一个元素(即待插入元素)。在第一部分排序完成后,再将这个最后元素插入到已排好序的第一部分中。
插入排序的基本思想是:每步将一个待排序的纪录,按其关键码值的大小插入前面已经排序的文件中适当位置上,直到全部插入完为止。
图例
这里写图片描述

2. 代码

package com.sort;public class InsertionSort {    private static int count = 20;//定义数组长度    private static int[] intArr;//定义数组    public static void main(String[] args) {        InsertionSort selectSort = new InsertionSort();        selectSort.initData();        selectSort.insertion_sort(intArr,0,count);        selectSort.showSortedArray();    }    /**     * 初始化数组     */    private void initData(){        intArr = new int[count];        System.out.println("intArr数组随机数为:");        for(int i=0;i<count;i++){            int temp = (int)(Math.random()*100);            intArr[i] = temp;            System.out.print(temp + ",");        }        System.out.println("\n"+"===============================================================");    }    private void insertion_sort(int array[],int first,int last) {        int i,j = 0;        int temp = 0;//定义变量,保存未排序的那个数        for(i=first+1;i<last;i++){//默认第一个数有序,从第二个数开始排序,i次排序后,保证前i-1个数有序,当i最小为1时,intArr[0]有序            temp = array[i];//赋值            j=i-1;//从排好序的最后开始往前依次比较            //与已排序的数逐一比较,大于temp时,该数后移            while((j>=first)&&(array[j]>temp)){//当first=0,j循环到-1时,由于【短路求值】,不会运算到array[-1]                array[j+1] = array[j];                j--;            }            array[j+1] = temp;        }    }    /**     * 排序完成后输出排序结果     */    private void showSortedArray() {        System.out.println("intArr排序完成后的排序结果是:");        for (int i = 0; i < intArr.length; i++) {            System.out.print(intArr[i] + ",");        }        System.out.println("\n" + "===============================================================");    }}------

3.输出结果
intArr数组随机数为:

34,35,85,30,29,7,97,5,16,69,90,14,3,5,69,98,14,10,53,8,

intArr排序完成后的排序结果是:

3,5,5,7,8,10,14,14,16,29,30,34,35,53,69,69,85,90,97,98,

Flash:

http://www.tjbpi.com/jpk/shujujiegou/flash/%B5%DA%CA%AE%D2%BB%D5%C2%20%C5%C5%D0%F2/%D6%B1%BD%D3%B2%E5%C8%EB%C5%C5%D0%F2.swf
视频:插入排序舞蹈

http://v.youku.com/v_show/id_XMjU4NTY5MzEy.html

0 0
原创粉丝点击