-
/* @(#)find_orderk.c
-
*/
-
#include <stdio.h>
-
int find_orderk1(const int* narray,const int n,const int k){
-
int top[k+1];
-
int i,j;
-
for(i=0; i<k+1; i++)
-
top[i]=-1000;
-
for(i=0; i<n; i++){
-
for(j=k; j>0; j--)
-
if(narray[i]>top[j-1])
-
top[j]=top[j-1];
-
else
-
break;
-
if(j!=k)
-
top[j]=narray[i];
-
}
-
return top[k-1];
-
}
-
-
void swap(int *a, int *b){
-
int tmp = *a;
-
*a = *b;
-
*b = tmp;
-
}
-
-
void shiftdown(int *narray, const int n, const int k){
-
int biggest=k;
-
if(2*k+1<n&&narray[biggest]<narray[2*k+1])
-
biggest = 2*k+1;
-
if(2*k+2<n&&narray[biggest]<narray[2*k+2])
-
biggest = 2*k+2;
-
if(biggest!=k){
-
swap(&narray[biggest], &narray[k]);
-
shiftdown(narray, n, biggest);
-
}
-
}
-
-
void shiftup(int *narray, const int n, const int k){
-
int bigger=k;
-
if(narray[bigger]<narray[k/2])
-
bigger = k/2;
-
if(bigger!=k/2){
-
swap(&narray[bigger], &narray[k/2]);
-
shiftup(narray, n, k/2);
-
}
-
}
-
-
void printheap(int *narray, const int n){
-
int i;
-
for(i=0; i<n; i++){
-
-
if(((i+2)&i)==0)
-
-
}
-
-
}
-
-
int find_orderk2(const int* narray,const int n,const int k){
-
int new_array[n];
-
int i;
-
//Build maxHeap
-
for(i=0; i<n; i++){
-
new_array[i]=narray[i];
-
shiftup(new_array, i+1, i);
-
}
-
for(i=1; i<k; i++){
-
swap(&new_array[0], &new_array[n-i]);
-
shiftdown(new_array, n-i-1, 0);
-
printheap(new_array, n-i-1);
-
}
-
return new_array[0];
-
}
-
-
int main(int argc, char *argv[]){
-
int array[]={1,5,2,98,3221,4532,3421,32143,5,68,-3, 65321,44,-34};
-
printf("\n%d\n", find_orderk2
(array,
sizeof(array
)/
sizeof(array
[0]),
6));
-
printf("\n%d\n", find_orderk1
(array,
sizeof(array
)/
sizeof(array
[0]),
6));
-
}
-