//你知道为什么快速排序的时间复杂度是nlgn吗?
We look at the array as a complete binary number and put it in a small heap,
The ordering of each node requires O (h), which is H, H is the height of the two fork tree of the fully corresponding node,
n is the total number of nodes, the row of a node needs O (h) times, then row n nodes?
and 2^h=n-1 (full binary tree nature);
->H=LOG2 (n); when there are N nodes that need to be sorted is N*LG (n),
The time complexity of getting a quick sort is n*log2 (N), here's 2 as E, so
The time complexity of getting a fast row is N*lg (N), which actually starts from the heap and can get results.
#include <iostream>using namespace STD;Template<TypeNameT>classtrist{ Public:typedefT Type_value;};Template<TypeNameTint_n>classminheap{Private:typedef TypeNameTrist<t>:: Type_value type_value; Public: Minheap (intM_data[]) {data =NewType_value[_n]; for(intI=0; i<_n;i++) {data[i] = M_data[i]; } size = _n;intn = _n/2; while(n>=0) {Startsort (n,data); n--; } }voidStartsort (intN,t *data) {inti = n;intj =2*i+1;intTemp while(j<size) {if(j+1<size && data[j]>data[j+1]) j=j+1;if(Data[i]>data[j]) {temp = Data[i]; Data[i] = Data[j]; DATA[J] = temp; } i=j; j=2*i+1; }} T GetTop () {inttemp = data[0]; data[0]=data[size-1]; size--; Startsort (0, data);returnTemp }voidShow () { for(intI=0; i<size;i++) {cout<<data[i]<<" "; }cout<<endl; }Private: T *data;intsize;};intMain () {inta[]={8,6,5,3,4,2,5,1}; minheap<int,8> MH (a); Mh. Show ();cout<<MH. GetTop () <<endl; Mh. Show ();return 0;}
Do you know why the time complexity of fast sorting is N*LG (n)?