插入排序法java实现

来源:互联网 发布:linux动态获取ip地址 编辑:程序博客网 时间:2024/05/22 03:19

插入排序

插入排序(Insertion Sort)是一种简单直观的排序算法。它的工作原理是通过构建有序序列,对于未排序数据,在已排序序列中从后向前扫描,找到相应位置并插入。插入排序在实现上,通常采用in-place排序(即只需用到O(1)的额外空间的排序),因而在从后向前扫描过程中,需要反复把已排序元素逐步向后挪位,为最新元素提供插入空间。

时间复杂度:O(n^2);

1.直接插入法

算法描述:
    1.从第一个元素开始,该元素可以认为已经被排序
    2.取出下一个元素,在已经排序的元素序列中从后向前扫描
    3.如果该元素(已排序)大于新元素,将该元素移到下一位置
    4.重复步骤3,直到找到已排序的元素小于或者等于新元素的位置
    5.将新元素插入到该位置后
    6.重复步骤2~5
动画演示

    

2.折半插入排序(参考之前的二分查找)

用折半查找方法确定插入位置的排序。思想类似直接插入排序,只不过,要设置 mid=不大于(low+high)/2的最大整数,当插入到 mid 左边(做半区),则改变 high(mid-1),如果插入到 mid 右边,则改变 low(mid+1)。

初试序列,同样是把第一个记录看成是有序的子序列,然后从第二个记录开始,依次进行比较

假设只有最后的20这个记录了

mid=(0+6)/2=3,指向39处,20比mid 的值小,插入到 mid 左边,改变 high=mid-1

重新计算 mid=1,指向13处,继续和20比较,20比 mid的值大,插入到 mid 右边,改变 low=mid+1

计算 mid=2,指向30,20比 mid 的值30小,插入到 mid 左边,改变 high=mid-1

直到low>high时,由折半查找得到的插入位置为low或high+1。


java代码实现直接插入排序:

package sortInsertDirec;/* * java链表实现直接插入排序 */public class SortInsertDirec {public int[] sort(int data[]){int out[]=new int[data.length];ListNode head=new ListNode(data[0]);ListNode temp=head;for(int i=1;i<data.length;i++){temp.next=new ListNode(data[i]);temp=temp.next;}ListNode curNode=head.next;ListNode curNextNode=null;head.next=null;while(curNode!=null){curNextNode=curNode.next;temp=head;ListNode tempPre=null;while(temp!=null){if(curNode.val>temp.val){break;}tempPre=temp;temp=temp.next;}if(tempPre==null){head=curNode;curNode.next=temp;}else{tempPre.next=curNode;curNode.next=temp;}curNode=curNextNode;}int mm=0;while(head!=null){out[mm]=head.val;mm++;head=head.next;}return out;}public class ListNode{int val;ListNode next;ListNode(int x){val=x;next=null;}}public static void main(String args[]){int data[]={7,3,8,7,9,1,6,2,10};SortInsertDirec sc=new SortInsertDirec();data=sc.sort(data);for(int i=0;i<data.length;i++){System.out.print(data[i]+" ");}}}


第二种实现方法:

package code.sortInsert;import code.sortList.*;public class Solution {    public ListNode insertionSortList(ListNode head) {    //哑节点        ListNode dumy = new ListNode(Integer.MIN_VALUE);        ListNode cur = head;        ListNode pre = dumy;        while (cur != null) {        //保存当前节点下一个节点        ListNode next = cur.next;            pre = dumy;            //寻找当前节点正确位置的一个节点            while (pre.next != null && pre.next.val < cur.val) {            pre = pre.next;            }            //将当前节点加入新链表中cur.next = pre.next;pre.next = cur;//处理下一个节点cur = next;        }        return dumy.next;        }        public static void main(String args[]){int data[]={7,3,8,7,9,1,6,2,10};Solution s=new Solution();ListNode head=new ListNode(data[0]);ListNode temp=head;for(int i=1;i<data.length;i++){temp.next=new ListNode(data[i]);temp=temp.next;}head=s.insertionSortList(head);int out[]=new int[data.length];int mm=0;while(head!=null){out[mm]=head.val;mm++;head=head.next;}for(int i=0;i<out.length;i++){System.out.print(out[i]+" ");}}}


0 0
原创粉丝点击