大学毕业后也没怎么写过博客了,最近公司项目不多,正好抽空能把之前的知识复习复习,发现大多都还给老师了_(:з)∠)_。以下代码段是这两天抽空复习的成果(查找那边可能还有些问题,抽空再看看吧= 。 =)。
#include<iostream>
using namespace std;
class sort{
//排序算法复习
public:
//冒泡排序
void maoPao(int arr[], int arrLen)
{
if (NULL == arr){
cout << "Please give a correct array" << endl;
}
else{
for (int i = 1; i < arrLen; i++){
for (int j = 0; j < arrLen - i; j++){
if (arr[j]>arr[j + 1]){
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
for (int ii = 0; ii < arrLen; ii++){
cout << arr[ii] << " ";
}
cout << endl;
}
};
};
class findNumByHalf{
public:
// 目標数の位置(二分法)
int findNum(int orderNum, int arr[], int min, int max){
cout << "数の範囲が" << min << "から" << max << "まで。" << endl;
if (min <= max){
int mid = (min + max) / 2;
if (orderNum == arr[mid]){
return mid;
}
else if (orderNum < arr[mid]){
findNum(orderNum, arr, min, mid - 1);
}
else if (orderNum > arr[mid]){
findNum(orderNum, arr, mid, max - 1);
}
}
else{
return -1;
}
}
};
//二叉树节点的定义
typedef struct Node{
char data;
struct Node* lChild;
struct Node* rChild;
}BTNode;
//二叉树的建立
void BuildBT(BTNode **tree){
char ch = '#';
cin >> ch;
if ('#' == ch){
*tree = NULL;
}
else{
*tree = (BTNode*)malloc(sizeof(BTNode));
(*tree)->data = ch;
BuildBT(&(*tree)->lChild);
BuildBT(&(*tree)->rChild);
}
}
//二叉树的销毁
void deleteTree(BTNode *tree){
if (NULL != tree){
deleteTree(tree->lChild);
deleteTree(tree->rChild);
free(tree);
}
}
//二叉树的遍历(先)
void preOrderFront(BTNode *node){
if (NULL == node){
return;
}
else{
cout<<node->data<<endl;
preOrderFront(node->lChild);
preOrderFront(node->rChild);
}
}
//二叉树的遍历(中)
void preOrderMid(BTNode *node){
if (NULL == node){
return;
}
else{
preOrderMid(node->lChild);
cout << node->data << endl;
preOrderMid(node->rChild);
}
}
//二叉树的遍历(后)
void preOrderAfter(BTNode *node){
if (NULL == node){
return;
}
else{
preOrderAfter(node->lChild);
preOrderAfter(node->rChild);
cout << node->data << endl;
}
}
//二叉树的高度
int treeHeight(BTNode *node){
int height = 0;
if (NULL == node){
return 0;
}
else{
int lHeight = treeHeight(node->lChild);
int rHeight = treeHeight(node->rChild);
height = (lHeight >= rHeight) ? lHeight + 1 : rHeight + 1;
}
return height;
}
void main(){
int arr[] = { 0, 1, 4, 6, 8, 3, 5, 8, 2, 11 };
int orderNum = 0;
BTNode* tree1;
//冒泡排序
sort *p = new sort();
findNumByHalf findNumBy2;
p->maoPao(arr, sizeof(arr) / sizeof(int));
//二分法
cout << "Please enter a num:" << endl;
cin >> orderNum;
int orderPosion = findNumBy2.findNum(orderNum, arr, 0, sizeof(arr) / 4);
cout << "この数の位置が" << orderPosion << "です。" << endl;
cout << "create tree" << endl;
BuildBT(&tree1);
cout << "二叉树的遍历(先)" << endl;
preOrderFront(tree1);
cout << "二叉树的遍历(中)" << endl;
preOrderMid(tree1);
cout << "二叉树的遍历(后)" << endl;
preOrderAfter(tree1);
cout << "二叉树的销毁" << endl;
deleteTree(tree1);
delete p;
system("pause");
}