Pagini recente » Cod sursa (job #510215) | Cod sursa (job #678682) | Cod sursa (job #2726282) | Cod sursa (job #45906) | Cod sursa (job #3179230)
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
typedef struct Node{
int key;
int dimension;
struct Node *left;
struct Node *right;
};
int GetDimension(Node *node){
if(NULL==node)
return 0;
return node->dimension;
}
void InsertInTree(Node **root,int key){
if(NULL==(*root)){
(*root)=(Node *) malloc(sizeof(Node));
(*root)->key=key;
(*root)->dimension=1;
(*root)->left=NULL;
(*root)->right=NULL;
return;
}
Node *curr_node=(*root);
bool ok=false;
while(!ok){
if(key>curr_node->key){
curr_node->dimension+=1;
if(NULL==curr_node->right){
Node *temp=(Node *) malloc(sizeof(Node));
temp->key=key;
temp->dimension=1;
temp->right=NULL;
temp->left=NULL;
curr_node->right=temp;
ok=true;
}
else curr_node=curr_node->right;
}
else if(key<curr_node->key){
curr_node->dimension+=1;
if(NULL==curr_node->left){
Node *temp=(Node *) malloc(sizeof(Node));
temp->key=key;
temp->dimension=1;
temp->right=NULL;
temp->left=NULL;
curr_node->left=temp;
ok=true;
}
else curr_node=curr_node->left;
}
}
}
void OS_SELECT(Node **root,int index){
Node *curr_node=(*root);
int rank= GetDimension(curr_node->left)+1;
while(rank!=index && curr_node!=NULL){
if(rank>index) curr_node=curr_node->left;
else {
curr_node=curr_node->right;
index=index-rank;
}
rank= GetDimension(curr_node->left)+1;
}
printf("%d",curr_node->key);
}
int Partition(int *arr,int low,int high){
int aux,piv=low;
while(low<=high){
while(arr[low]<arr[piv])
low++;
while(arr[high]>arr[piv])
high--;
if(low<high){
aux=arr[low];
arr[low]=arr[high];
arr[high]=aux;
low++;
high--;
}
else break;
}
aux=arr[high];
arr[high]=arr[piv];
arr[piv]=aux;
return high;
}
void QuickSelect(int *arr,int low,int high,int k){
if(low<high){
int rand_index=rand()%(high-low)+low;
int p=arr[low];
arr[low]=arr[rand_index];
arr[rand_index]=p;
p= Partition(arr,low,high);
if(p<k) QuickSelect(arr,p+1,high,k);
else if(p>k) QuickSelect(arr,low,p-1,k);
}
}
int main() {
freopen("sdo.in","r",stdin);
freopen("sdo.out","w",stdout);
// Node *root=NULL;
int N,k;
scanf("%d",&N);
int *arr=(int *) malloc(sizeof(int)*N);
scanf("%d",&k);
for(int i=0;i<N;i++) {
scanf("%d",&arr[i]);
// InsertInTree(&root,arr[i]);
}
srand(time(NULL));
QuickSelect(arr,0,N-1,k-1);
printf("%d",arr[k-1]);
//OS_SELECT(&root,k);
free(arr);
return 0;
}