---
title: "用c++实现二叉树增删改查和快速排序算法"
author: "yunchow"
date: "2009-06-02T13:18:43Z"
tags: ["C", "C#", "C++", "算法"]
slug: "c"
draft: false
lastmod: "2009-06-02T13:19:26Z"
id: 400263
url: "https://yunchow.iteye.com/blog/400263"
---

\[code="c++"] //快速排序 #include using namespace std; #define N 10240 template&lt; typename T &gt; void sort( T* a, int n ){ if(n&lt;=0) return; if(n==2) { if(a\[1] &lt; \*a) swap(a\[1],\*a); return; } swap( \*a,a\[n&gt;&gt;1] ); T v = \*a; T* left = a+1; T* right = a+n-1; while( leftv&&right&gt;a ) --right; if( left using namespace std; template&lt; typename T &gt; 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 &lt;&lt; "~BanaryTree()" &lt;&lt; endl; } void push(const T& t ){ Node* p = new Node(t); insert(root, p ); } bool empty(){ return root==NULL; } void travel(){ show(root); cout &lt;&lt; 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-&gt;right, q-&gt;left ); q = q-&gt;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-&gt;data == p-&gt;data ) return tree; else if(p-&gt;data &lt; tree-&gt;data ) return find( tree-&gt;left, p); else return find( tree-&gt;right, p); } int size( Node* tree ){ if(!tree) return 0; return size(tree-&gt;left) + size(tree-&gt;right) + 1; } void show(const Node* tree){ if(!tree) return; show(tree-&gt;left); cout &lt;&lt; tree-&gt;data &lt;&lt; ' '; show(tree-&gt;right); } void insert( Node\*& tree,Node* p){ if(!tree) tree = p; else if(p-&gt;datadata) insert(tree-&gt;left,p); else insert(tree-&gt;right, p); } void clear(Node\*& tree){ if( empty() ) return; if( !tree ) return; clear( tree-&gt;left ); clear( tree-&gt;right ); delete tree; tree = NULL; } }; //the end of class int main() { BanaryTree bi; for(int i=0; i&lt;10; i++) bi.push(10-i); bi.travel(); cout &lt;&lt; "size() : " &lt;&lt; bi.size() &lt;&lt; endl; cout &lt;&lt; "find(5) : " &lt;&lt; bi.find(5) &lt;&lt; endl; cout &lt;&lt; "find(100) : " &lt;&lt; bi.find(100) &lt;&lt; endl; bi.erase(6); bi.travel(); bi.erase(50); bi.travel(); bi.update(10,11); bi.travel(); bi.update(10,11); bi.travel(); }\[/code]