堆排序,快速排序
大根堆排序算法的基本操作:?
① 初始化操作:將R[1..n]構(gòu)造為初始堆;
② 每一趟排序的基本操作:將當(dāng)前無(wú)序區(qū)的堆頂記錄R[1]和該區(qū)間的最后一個(gè)記錄交換,然后將新的無(wú)序區(qū)調(diào)整為堆(亦稱重建堆)。
注意:?
①只需做n-1趟排序,選出較大的n-1個(gè)關(guān)鍵字即可以使得文件遞增有序。
②用小根堆排序與利用大根堆類似,只不過(guò)其排序結(jié)果是遞減有序的。堆排序和直接選擇排序相反:在任何時(shí)刻堆排序中無(wú)序區(qū)總是在有序區(qū)之前,且有序區(qū)是在原向量的尾部由后往前逐步擴(kuò)大至整個(gè)向量為止。
注意:1,每次新建的大根堆放到有序序列里。2,新建大根堆注意根和孩子比較過(guò)后還需要比較孩子和孫子。
1 import java.util.*; 2 public class HeapSort { 3 public void exchageElement(int[] a, int index1, int index2){ 4 int temp = a[index1]; 5 a[index1] = a[index2]; 6 a[index2] = temp; 7 } 8 public void heapSort(int[] a,int lastIndex){ 9 if(a.length == 0) return ; 10 for(int i=(lastIndex-1)/2;i>=0;i--){ 11 int k = i; //最后一個(gè)非葉子節(jié)點(diǎn) 12 while(2*k+1<=lastIndex){ 13 int maxIndex = 2*k+1;//把左孩子暫時(shí)當(dāng)成最大 14 if(maxIndex<lastIndex){ 15 //證明有右節(jié)點(diǎn) 16 if(a[maxIndex]<a[maxIndex+1])maxIndex++; //如果右節(jié)點(diǎn)比左節(jié)點(diǎn)要大則最大孩子為右節(jié)點(diǎn)(用maxIndex++來(lái)提高時(shí)間復(fù)雜度) 17 } 18 if(a[maxIndex]>a[k]){ 19 new HeapSort().exchageElement(a,maxIndex,k); 20 k=maxIndex; 21 }else{ 22 break; 23 24 } 25 } 26 } 27 28 } 29 public static void main (String[] args) { 30 Scanner sc = new Scanner(System.in); 31 int n = sc.nextInt(); 32 int[] arrInt = new int[n]; 33 for(int i = 0;i<n;i++){ 34 arrInt[i] = sc.nextInt(); 35 } 36 HeapSort hs=new HeapSort(); 37 for(int i=arrInt.length-1;i>0;i--){ 38 hs.heapSort(arrInt,i); 39 hs.exchageElement(arrInt,0,i); 40 } 41 42 System.out.println (Arrays.toString(arrInt)); 43 } 44 }快速排序算法的基本操作:
分析:快速排序是冒泡排序的一種升級(jí),打怪打不過(guò)咱們升級(jí)吧···宗旨是一趟排序下來(lái)可以交換多個(gè)元素,時(shí)間復(fù)雜度為O(logn).
?
??
轉(zhuǎn)載于:https://www.cnblogs.com/ScarecrowAnBird/p/6755758.html
總結(jié)
- 上一篇: s2sh删掉原本的s2sh projec
- 下一篇: 关于github上开源nineoldan