三、插入排序

来源:互联网 发布:培训管理数据流程图 编辑:程序博客网 时间:2024/06/09 23:26

1、算法原理
插入排序是将一个数据插入到已经排好序的有序数据中,从而得到一个新的、个数加一的有序数据。此算法适用于少量数据的排序,时间复杂度为O(n^2),空间复杂度为O(1)。插入排序是稳定的排序算法。

2、代码实现
(1)JAVA实现
注:本程序设计生成10个随机数,再对这10个随机数进行从小到大的插入排序

/* * 排序算法:插入排序 * 作者:xiaoxiao * 日期:2016-03-17 */import java.util.Random;public class InsertSort {    public static void main(String[] args) {        //定义可以存10个数的数组        int[] arr = new int[10];        int[] rs = new int[10];        init(arr);        System.out.print("排序前:");        for (int i = 0; i < arr.length; i++) {            System.out.print(arr[i] + ", ");        }        System.out.println();        rs = insertSort(arr);        System.out.print("排序后:");        for (int i = 0; i < rs.length; i++) {            System.out.print(rs[i] + ", ");        }    }    public static void init(int[] a) {        Random r = new Random();        for (int i = 0; i < a.length; i++) {            a[i] = r.nextInt(100);        }    }    public static int[] insertSort(int[] a) {        if (a == null || a.length < 2) {            return a;        }        int tmp;        for (int i = 1; i < a.length; i++) {            //对前i-1个数据进行逐一遍历比较,将第i个数插入到恰当位置            for (int j = i; j > 0; j--) {                if (a[j] < a[j - 1]) {                    tmp = a[j];                    a[j] = a[j - 1];                    a[j - 1] = tmp;                } else {                    break;                }            }        }        return a;    }}

运行结果:
这里写图片描述

(2)PHP实现
注:本程序设计随机生成10~20个1~100的数,再对这些数进行从小到大的插入排序

<!--Method:插入排序Author: xiaoxiaoDate: 2016-03-17--><?php        echo "<meta http-equiv='Content-Type' content='text/html; charset=utf-8' />";//如果涉及到PHP网页中文乱码问题,加上该行        function InsertSort($a){                $length = count($a);                for($i = 1; $i < $length; $i++){                        //对第i+1~$length的数字进行查找,找到最小数字对应的坐标                        for ($j = $i; $j > 0; $j--) {                                if ($a[$j] < $a[$j-1]) {                                        $temp = $a[$j];                                        $a[$j] = $a[$j-1];                                        $a[$j-1] = $temp;                                }                                else{                                        break;                                }                        }                }                return $a;        }        $a = array();        $nums = mt_rand(10,20);        for ($i = 0; $i < $nums; $i++) {                 array_push($a, mt_rand(1,100));        }        echo "待排序的数有".$nums."个!<br />";        echo "排序前: ";        for($i = 0; $i < count($a); $i++){                echo $a[$i];                echo ", ";        }        echo "<br />";        echo "排序后:  ";        $b = InsertSort($a);        for($i = 0; $i < count($b); $i++){                echo $b[$i];                echo ", ";        }?>

运行结果:
这里写图片描述

原创粉丝点击