BST && TREAP 实现简单排序

//BST
#include<stdio.h>
#include<stdlib.h>
struct node{
	int x;
	struct node *left,*right;
};
struct node *h,*p,*q;
void insert(int s,struct node *t){
	if(s>t->x){
		if(t->right==NULL){
			q=new node;
			q->x=s;q->left=NULL;q->right=NULL;
			t->right=q;
		}else	insert(s,t->right);		
	}else{
		if(t->left==NULL){
			q=new node;
			q->x=s;q->left=NULL;q->right=NULL;
			t->left=q;
		}else insert(s,t->left);	
	}
}

void dfs(struct node *t){
	if(t==NULL)return;
	dfs(t->left);
	printf("%d ",t->x);
	dfs(t->right);
}

int main(){
	int i,j,k,m,n;
	
	scanf("%d",&n);
	scanf("%d",&k);
	h=new node;
	h->x=k;h->left=NULL;h->right=NULL;	
	for(i=2;i<=n;i++){
		scanf("%d",&k);		
		insert(k,h);
	}	
	dfs(h);
	system("pause");
	return 0;
}


//TREAP
#include<iostream>
#include<cstdio>
#include<cstdlib>
using namespace std;
struct node{
	int x,w;	
	struct node *h,*r,*l;
	node(){
		x=0;w=0;h=r=l=NULL;
	}
};
node *root;
void zrg(node *u,node *v){
	node *t=u->h;
	u->l=v->r;if(v->r!=NULL)v->r->h=u;
	u->h=v;v->r=u;
	v->h=t;
	if(t!=NULL){	
		if(t->l==u)t->l=v;
		else t->r=v;
	}else root=v;
}
void zlg(node *u,node *v){
	node *t=u->h;
	u->r=v->l;if(v->l!=NULL)v->l->h=u;
	v->l=u;u->h=v;
	v->h=t;
	if(t!=NULL){	
		if(t->l==u)t->l=v;
		else t->r=v;
	}else root=v;
}
void out(node *u){
	if(u!=NULL){
		out(u->l);
		printf("%d ",u->x);
		out(u->r);
	}
}
void insert(node *u,node *v){
	if(u==NULL)return;
	if(v->x>u->x){
		if(u->r==NULL){
			u->r=v;v->h=u;
			while(v->h!=NULL && v->w<v->h->w){
				if(v==v->h->r)zlg(v->h,v);
				else zrg(v->h,v);
			}			
		}else insert(u->r,v);			
	}else{
		if(u->l==NULL){
			u->l=v;v->h=u;
			while(v->h!=NULL && v->w<v->h->w){
				if(v==v->h->r)zlg(v->h,v);
				else zrg(v->h,v);
			}			
		}else insert(u->l,v);	
	}
}

int main(){
	int i,j,k,m,n,t;
	node *p,*q;
	cin>>n;	
	cin>>k;
	srand(3433);
	root=new node;
	root->x=k;root->w=rand();
	for(i=2;i<=n;i++){
		cin>>k;
		q=new node;
		q->x=k;q->w=rand();		
		insert(root,q);			
	}	
	out(root);
	return 0;
}


  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值