文章目录
13、将一个从大到小的数组,用以下排序方法排序成从小到大的,______最快。
A.插入排序
B.冒泡排序
C.快速排序
D.堆排序
该题假如是单问算法复杂度,无疑是C和D,都是O(n*logn),但是在初始化时降序的情况下,就得另外考虑了,其实可以发现这个降序的数组对C,和D并无价值,并且还增加了排序时的比较次数,现在来看插入排序:
有一个已经有序的数据序列,要求在这个已经排好的数据序列中插入一个数,但要求插入后此数据序列仍然有序,这个时候就要用到一种新的排序方法
根据待排序数组是降序的情况下很容易想到插排在每次插入是只需要比较第一个元素即可,因为前面的元素都比他大,一般插入排序是基于数组实现的,每次在插入一个元素时需要将插入后的元素都向后移动一位,如果这样其复杂度也不会减少,这种可以下可以将插排基于链表来实现,这样就不需要移动数组了。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119
| /** * 插入排序,基于链表的实现 * @author Administrator * */ public class InsertionSort { public static void main(String[] args) { int[] nums={6,3,5,4,2,9,1}; System.out.println(new InsertionSort().sort(nums)); for(int i=0;i<nums.length;i++) { System.out.print(nums[i]); } System.out.println(); int[] nums2={9,6,5,4,3,2,1}; System.out.println(new InsertionSort().sort(nums2)); for(int i=0;i<nums.length;i++) { System.out.print(nums2[i]); } } /** * 进行数组排序 返回循环次数 * @param nums * @return */ public int sort(int[] nums) { Node linkedList=createLinkedList(nums); Node cur=linkedList,head=linkedList,prev; int loopCount=0; do{ prev=cur; cur=cur.next; }while(cur!=null && prev.val<cur.val); while(cur!=null) { Node p=null; Node q=head; int tempLoop=0; while(q!=null && cur.val>q.val && cur!=q) { tempLoop++; p=q; q=q.next; } loopCount+=tempLoop==0?1:tempLoop; if(cur!=q) { prev.next=cur.next; if(p==null) { cur.next=q; head=cur; }else{ p.next=cur; cur.next=q; } cur=prev.next; }else{ prev=cur; cur=cur.next; } } for(int i=0;i<nums.length;i++) { nums[i]=head.val; head=head.next; } return loopCount; } /** * 创建链表 返回链表的头部 * @param nums * @return */ private Node createLinkedList(int[] nums) { Node head=null; for(int i=nums.length-1;i>=0;i--) { Node node=new Node(nums[i],head); head=node; } return head; } static class Node{ public int val; public Node next; public Node(int val,Node next) { this.val=val; this.next=next; } public boolean hasNext() { return this.next!=null; } } }
|
实验结果:
10
1234569
6
1234569
本作品采用[知识共享署名-非商业性使用-相同方式共享 2.5]中国大陆许可协议进行许可,我的博客欢迎复制共享,但在同时,希望保留我的署名权kubiCode,并且,不得用于商业用途。如您有任何疑问或者授权方面的协商,请给我留言。