intKthBig(int A[],int i,int j,int kBig){ int count = 0; if (j <= i || A == NULL) return-1; int pivotIndex = (i+j)/2; swap(A,pivotIndex,j); int index = partition0(A,i-1,j,A[j]); // k is index swap(A,index,j); count = index - i + 1; // count the k big data if (kBig == count) { return index; } elseif(count > kBig){ return KthBig(A, i, index, kBig); } else{ return KthBig(A, index, j, kBig-count); } }
constint MAX_N = 100; int heap[MAX_N],sz=0; //sz is global variable, meaning the lengh of heap
voidheap_push(int x){ //own node's num. int node_index = sz++; while (node_index > 0) { int p = (node_index-1)/2; //i's parent if (heap[p] >= x) { break; // sequence is ok } // parent's value put down, node value go up heap[node_index] = heap[p]; node_index = p; } heap[node_index] = x; }
intheap_pop(){ // max (root) int rec = heap[0]; // The value to put in the root int x = heap[--sz]; //Swap from root int i = 0; while (i*2+1 < sz) { //compare the children value int a = i*2+1; // left child int b = i*2+2; // right child if (b < sz && heap[b] > heap[a]) { a = b; } // sequence is right if (heap[a] <= x) { break; } // child's value go up heap[i] = heap[a]; i=a; } heap[i] = x; return rec; }
intmain(){ //push(3); heap_push(9); heap_push(2); heap_push(6); for (int i=0; i<sz; i++) { cout<<heap[i]<<endl; } cout<<"pop:"<<heap_pop()<<endl; // also we can use library priority_queue<int> qqueue; qqueue.push(9); qqueue.push(2); qqueue.push(6); //loop until it is empty while (!qqueue.empty()) { cout<<qqueue.top()<<endl; qqueue.pop(); } return0; }