日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

堆排序,快速排序

發布時間:2025/3/15 编程问答 16 豆豆
生活随笔 收集整理的這篇文章主要介紹了 堆排序,快速排序 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

大根堆排序算法的基本操作:?

① 初始化操作:將R[1..n]構造為初始堆;

② 每一趟排序的基本操作:將當前無序區的堆頂記錄R[1]和該區間的最后一個記錄交換,然后將新的無序區調整為堆(亦稱重建堆)。

注意:?

①只需做n-1趟排序,選出較大的n-1個關鍵字即可以使得文件遞增有序。

②用小根堆排序與利用大根堆類似,只不過其排序結果是遞減有序的。堆排序和直接選擇排序相反:在任何時刻堆排序中無序區總是在有序區之前,且有序區是在原向量的尾部由后往前逐步擴大至整個向量為止。

注意:1,每次新建的大根堆放到有序序列里。2,新建大根堆注意根和孩子比較過后還需要比較孩子和孫子。

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; //最后一個非葉子節點 12 while(2*k+1<=lastIndex){ 13 int maxIndex = 2*k+1;//把左孩子暫時當成最大 14 if(maxIndex<lastIndex){ 15 //證明有右節點 16 if(a[maxIndex]<a[maxIndex+1])maxIndex++; //如果右節點比左節點要大則最大孩子為右節點(用maxIndex++來提高時間復雜度) 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 }

快速排序算法的基本操作:

  分析:快速排序是冒泡排序的一種升級,打怪打不過咱們升級吧···宗旨是一趟排序下來可以交換多個元素,時間復雜度為O(logn).

  • 把數組的首個元素a[0]存到temp中作為第一次排序的比較對象,j表示從右到左進行比較的下標,發現比temp大則與第i個元素交換(恰好第i個元素放到temp作為基準比較元素);i表示從左到右比較的下標,發現比temp小則與第j個元素交換(此時j個元素已經復制到前面了)。如此下去直到i==j為止,一趟排序結束。
  • 這樣一趟排序結束后分成兩個數組分別進行排序,重復第一步。
  • 注意:快排兩端節點分析
  • 1 import java.util.*; 2 public class kuaipai { 3 public static void main (String[] args) { 4 Scanner sc = new Scanner(System.in); 5 while(sc.hasNext()){ 6 int n = sc.nextInt(); 7 int[] arrInt = new int[n]; 8 for(int i = 0;i<n;i++){ 9 arrInt[i] = sc.nextInt(); 10 } 11 int i=0;int j=n-1; 12 kuaipai kp = new kuaipai(); 13 kp.kuaiP(arrInt,i,j); 14 15 System.out.print(Arrays.toString(arrInt)); 16 } 17 } 18 public void kuaiP(int[] a, int i, int j){ 19 int low = i; 20 int hight = j; 21 if(low>=hight) return ; 22 int temp = a[low]; 23 while(low<hight){ 24 while(a[hight]>=temp&&low<hight) hight--; 25 a[low] = a[hight]; 26 while(a[low]<=temp&&low<hight) low++; 27 a[hight] = a[low]; 28 } 29 a[low] = temp; 30 kuaiP(a,0,low-1); 31 kuaiP(a,low+1,j); 32 } 33 }

    ?

    ?

    ?

  • 轉載于:https://www.cnblogs.com/ScarecrowAnBird/p/6755758.html

    總結

    以上是生活随笔為你收集整理的堆排序,快速排序的全部內容,希望文章能夠幫你解決所遇到的問題。

    如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。