1.堆排序
#include<iostream>
using namespace std;
#include<ctime>
#define MAX 100
void myprint(int tree[], int len)
{
for (int i = 0; i < MAX; i++)
{
cout << tree[i] << " ";
}
}
void swap(int tree[], int i, int j)
{
int temp = tree[i];
tree[i] = tree[j];
tree[j] = temp;
}
//调整为大顶堆
void adjustheap(int tree[], int len, int i)
{
int max = i;
int lc = 2 * i + 1;
int rc = 2 * i + 2;
if (lc < len && tree[lc] > tree[max])
{
max = lc;
}
if (rc < len && tree[rc] > tree[max])
{
max = rc;
}
if (max != i)
{
swap(tree, i, max);
adjustheap(tree, len, max);
}
}
//初始化堆
void heapfiy(int tree[], int len)
{
for (int i = (len - 1) / 2; i >= 0; i--)
{
adjustheap( tree, MAX, i);
}
}
void heapsort(int tree[], int len)
{
heapfiy(tree, MAX);
//交换根与最大下表节点的位置
for (int i = len - 1; i >= 0; i--)
{
swap(tree, 0, i);
adjustheap(tree, i, 0);
}
}
int main()
{
srand((unsigned int)time(NULL));
int tree[MAX];
for (int i = 0; i < MAX; i++)
{
tree[i] = rand() % MAX;
}
heapsort(tree, MAX);
myprint(tree, MAX);
return 0;
}
2.快排:
void qs(vector<int>& nums, int start, int end) {
if (start < end) {
int low = start, high = end;
int tmp = nums[low];
while (low < high) {
while (low < high && nums[high] >= tmp) high--;
if (low < high) nums[low++] = nums[high];
while (low < high && nums[low] <= tmp) low++;
if (low < high) nums[high--] = nums[low];
}
nums[low] = tmp;
qs(nums, start, low - 1);
qs(nums, low + 1, end);
}
}
3.二分查找:
int func(vector<int>& a,int target) {
int left = 0, right = a.size() - 1;
while (left <= right) {
int mid = left + ((right - left) / 2);
if (target < a[mid]) right = mid - 1;
else if (target > a[mid]) left = mid + 1;
else return mid;
}
return -1;
}
4.智能指针
template<typename T>
class SharedPtr
{
public:
SharedPtr(T* ptr = NULL):_ptr(ptr), _pcount(new int(1))
{}
SharedPtr(const SharedPtr& s):_ptr(s._ptr), _pcount(s._pcount){
(*_pcount)++;
}
SharedPtr<T>& operator=(const SharedPtr& s){
if (this != &s)
{
if (--(*(this->_pcount)) == 0)
{
delete this->_ptr;
delete this->_pcount;
}
_ptr = s._ptr;
_pcount = s._pcount;
*(_pcount)++;
}
return *this;
}
T& operator*()
{
return *(this->_ptr);
}
T* operator->()
{
return this->_ptr;
}
~SharedPtr()
{
--(*(this->_pcount));
if (*(this->_pcount) == 0)
{
delete _ptr;
_ptr = NULL;
delete _pcount;
_pcount = NULL;
}
}
private:
T* _ptr;
int* _pcount;//指向引用计数的指针
};
5.单例模式
class A {
private:
A() {
a = new A;
}
public:
static A* getInstance() {
return a;
}
//懒汉模式
/*
static A* getInstance() {
if(a == NULL) {
a = new A;
}
return a;
}
*/
private:
static A* a;
};
A* A::a = NULL;
6,几种构造函数
class Person {
public:
Person() {
cout << "无参构造函数!" << endl;
mAge = 0;
}
Person(int age) {
cout << "有参构造函数!" << endl;
mAge = age;
}
Person(const Person& p) {
cout << "拷贝构造函数!" << endl;
mAge = p.mAge;
}
Person & operator=(const Person &p){
cout << "赋值函数!" << endl;
mAge = p.mAge;
}
//析构函数在释放内存之前调用
~Person() {
cout << "析构函数!" << endl;
}
public:
int mAge;
};