1 / 14

HW9 summarization

HW9 summarization. 杨国东 November 16, 2005. 9.1 求两个排列好的数表的中位数. 给定数组 A 和 B ,长度为 n ,数组已经按非降序排列 要求时间复杂度为 O ( lgn ) 算法思想:分治. A. B. A1. A1. A2. B1. B2. B2. A12. A11. B12. B11. 算法思想. A[m]>B[m]. lgn. A1[m]<B1[m]. …. //A,B 为有 N 元素的整数数组 int findNth(int N, int A[], int B[]){

aelwen
Download Presentation

HW9 summarization

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. HW9 summarization 杨国东 November 16, 2005

  2. 9.1求两个排列好的数表的中位数 • 给定数组A和B,长度为n,数组已经按非降序排列 • 要求时间复杂度为O(lgn) • 算法思想:分治

  3. A B A1 A1 A2 B1 B2 B2 A12 A11 B12 B11 算法思想 A[m]>B[m] lgn A1[m]<B1[m] …

  4. //A,B为有N元素的整数数组 int findNth(int N, int A[], int B[]){ int Ai = 0, Aj = N-1;//记录A中保留段位置 int Bi = 0, Bj = N-1; int midA = N/2, midB = N - 1 - midA;//取保留段的中间位置 do{ if(A[midA] >= B[midB]){ Aj = midA - 1; Bi = midB + 1; }else{ Ai = midA + 1; Bj = midB - 1; }//裁减最大段和最小段 midA = (Ai + Aj )/2; midB = Bj - (midA - Ai);//使得裁减部分正好为一半 }while(Ai != Aj); if(A[Ai] <= B[Bi]){ return A[Ai]; }else{ return B[Bi]; } }

  5. 复杂度分析 • T( n ) = T( n/2 ) + C • T( n ) = O( lgn )

  6. 9.2给定整形数组A • 6,2,9,7,3,8,4,5,0,1 • Q1:取6作分割数,写出快速排序第一次分割后A中结果 • Q2:用堆排序将第一个选出的数据放在A的最后位置上将A调成堆后A中的结果 • Q3:用基数为3的基数排序法,写出第一次分配和收集后A中的结果

  7. 6 6 2 9 7 3 8 4 5 0 1 1 2 9 7 3 8 4 5 0 6 1 2 9 7 3 8 4 5 0 6 1 2 9 7 3 8 4 5 0 9 1 2 0 7 3 8 4 5 0 9 Q1以6为分割数的快速排序第一步

  8. 6 1 2 0 7 3 8 4 5 0 9 1 2 0 7 3 8 4 5 7 9 1 2 0 5 3 8 4 5 7 9 1 2 0 5 3 8 4 8 7 9

  9. 6 1 2 0 5 3 4 4 8 7 9 1 2 0 5 3 4 4 8 7 9 1 2 0 5 3 4 6 8 7 9 所以答案为:1,2,0,5,3,4,6,8,7,9

  10. 6 1 2 6 5 0 1 7 3 2 4 5 8 8 0 9 7 3 4 9 Q2堆排序 • 用堆排序将第一个选出的数据放在A的最后位置上将A调成堆后A中的结果 最大值堆建堆结果 取出最大值

  11. 0 8 9 7 3 4 2 1 5 6 7 3 4 2 8 5 1 6 0 调整 所以答案为:8,7,6,5,3,1,4,2,0,9

  12. Q3:基数为3的基数排序 • 用基数为3的基数排序法,写出第一次分配和收集后A中的结果 6,2,9,7,3,8,4,5,0,1 • 首先根据基数将原来的数据用基数对应的进制表示(0,1,2)6(020),2(002),9(100),7(021),3(010), 8(022),4(011),5(012),0(000),1(001) • 采用低位优先进行基数排序

  13. 6(020),2(002),9(100),7(021),3(010) 8(022),4(011),5(012),0(000),1(001) 020 100 010 000 021 011 001 002 022 012 100 000 001 002 010 011 012 020 021 022 000 001 002 010 011 012 020 021 022 100 所以答案为:6,9,3,0,7,4,1,2,8,5

  14. The end!

More Related