用c++实现二叉树增删改查和快速排序算法


//快速排序
#include <iostream>
using namespace std;
#define N 10240
template< typename T >
void sort( T* a, int n ){
if(n<=0) return;
if(n==2) {
if(a[1] < *a) swap(a[1],*a);
return;
}
swap( *a,a[n>>1] );
T v = *a;
T* left = a+1;
T* right = a+n-1;
while( left<right ){
while( left<right&&*left<v ) ++left;
while( *right>v&&right>a ) --right;
if( left<right ) swap(*left,*right );
}
swap( *a, *right );
sort( a, right-a );
sort( right+1, n-1-(right-a) );
}

int main()
{
int a[N];
for( int i=0; i<N; i++)
a[i] = N-i;
time_t t = time(NULL);
sort(a,N);
cout << "Time : " << time(NULL)-t << endl;
for( int i=0; i<10; i++)
cout << a[i] << ' ' ;
cout << endl;
}




//二叉树
#include <iostream>
using namespace std;

template< typename T >
class BanaryTree{
private:
struct Node{
T data;
Node* left;
Node* right;
Node():data(T()),left(NULL),right(NULL){ }
Node(const T& t):data(t),left(NULL),right(NULL){ }
}; // the end of struct

Node* root;
public:
BanaryTree():root(NULL){ }
~BanaryTree(){
clear(root);
cout << "~BanaryTree()" << endl;
}
void push(const T& t ){
Node* p = new Node(t);
insert(root, p );
}
bool empty(){
return root==NULL;
}
void travel(){
show(root);
cout << endl;
}
int size(){
return size(root);
}
bool find( const T& t ){
Node* p = new Node(t);
return find(root, p)!=NULL;
}
void erase( const T& t ){
Node* p = new Node(t);
Node*& q = find(root,p);
if(!q) return;
Node* r = q;
insert( q->right, q->left );
q = q->right;
delete r;
}
void update(const T& o, const T& n){
if( !find(o) ) return;
erase(o);
push(n);
}
private:
Node*& find( Node*& tree,Node*& p ){
if(!tree) return tree;
else if(!p) return p;
else if( tree->data == p->data ) return tree;
else if(p->data < tree->data )
return find( tree->left, p);
else return find( tree->right, p);
}
int size( Node* tree ){
if(!tree) return 0;
return size(tree->left) + size(tree->right) + 1;
}
void show(const Node* tree){
if(!tree) return;
show(tree->left);
cout << tree->data << ' ';
show(tree->right);
}
void insert( Node*& tree,Node* p){
if(!tree) tree = p;
else if(p->data<tree->data) insert(tree->left,p);
else insert(tree->right, p);
}
void clear(Node*& tree){
if( empty() ) return;
if( !tree ) return;
clear( tree->left );
clear( tree->right );
delete tree;
tree = NULL;
}
}; //the end of class

int main()
{
BanaryTree<int> bi;
for(int i=0; i<10; i++)
bi.push(10-i);
bi.travel();
cout << "size() : " << bi.size() << endl;
cout << "find(5) : " << bi.find(5) << endl;
cout << "find(100) : " << bi.find(100) << endl;
bi.erase(6);
bi.travel();
bi.erase(50);
bi.travel();
bi.update(10,11);
bi.travel();
bi.update(10,11);
bi.travel();
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值