算法汇总
算法具有的特征:有限性、确定性、可行性、输入性、输出性
typedef struct BNode
{
int date;
struct BNode* lchild, * rchild;
}BTNode;
int Submt(BTNode* bt)
{
if (bt->lchild == NULL && bt->rchild == NULL)
return bt->date;
return Submt(bt->lchild) + Submt(bt->rchild) + bt->date;
}
递归求解数组最大值:
int fmax(int a[], int i)
{
if (i == 1)
return a[0];
return max(fmax(a, i - 1),a[i-1]);
}
递归删除单链表中所有数据:
void Destroy(ListNode* p)
{
if (p->next != NULL)
{
Destroy(p);
free(p);
}
}
二叉树递归查找x路径
bool Findxpath(BTNode *bt, int x, vector<int> temp, vector<int>& path)
{
if (bt == NULL)
return false;
temp.push_back(bt->date);
if (bt->date == x)
{
path = temp;
return true;
}
bool find = Findxpath(bt->lchild, x, temp, path);
if (find)
return true;
Findxpath(bt->rchild, x, temp, path);
}
递归输出各个位数的数字
void Find(int n)
{
if (n != 0)
{
Find(n / 10);
printf("%d", n % 10);
}
}
选择排序算法
void SelectSort(int a[], int n, int i)
{
int j,k;
if (i == n - 1)
return;
k = i;
for (j = i + 1; j < n; j++)
{
if (a[k] > a[j])
k = j;
}
if (k != i)
swap(a[i], a[k]);
SelectSort(a, n, i + 1);
}
分治法的时间复杂度
快速排序用分治法实现:
int Partitionx(int a[], int s, int t)
{
int i = s , j = t;
int tmp = a[s]; //用序列的第1个记录作为基准
while (i != j) //从序列两端交替向中间扫描,直至i=j为止
{
while (j > i && a[j] >= tmp)
j--; //从右向左扫描,找第1个关键字小于tmp的a[j]
a[i] = a[j]; //将a[j]前移到a[i]的位置
while (i < j && a[i] <= tmp)
i++; //从左向右扫描,找第1个关键字大于tmp的a[i]
a[j] = a[i]; //将a[i]后移到a[j]的位置
}
a[i] = tmp;
return i;
}
void QuickSort(int a[], int l, int r)
{
if (r <= l) return;
int i = Partitionx(a, l, r);
QuickSort(a, l, i - 1);
QuickSort(a, i + 1, r);
}
自顶向下的二路归并排序算法
void Merge(int a[],int low,int mid,int high)
//a[low..mid]和a[mid+1..high]→a[low..high]
{
int* tmpa;
int i = low,j = mid + 1,k = 0;
tmpa = (int*)malloc((high - low + 1) * sizeof(int));
while (i <= mid && j <= high)
if (a[i] <= a[j]) //将第1子表中的元素放入tmpa中
{
tmpa[k] = a[i]; i++; k++;
}
else //将第2子表中的元素放入tmpa中
{
tmpa[k] = a[j]; j++; k++;
}
while (i <= mid) //将第1子表余下部分复制到tmpa
{
tmpa[k] = a[i]; i++; k++;
}
while (j <= high) //将第2子表余下部分复制到tmpa
{
tmpa[k] = a[j]; j++; k++;
}
for (k = 0,i = low; i <= high; k++,i++) //将tmpa复制回a中
a[i] = tmpa[k];
free(tmpa); //释放tmpa所占内存空间
}
void MergePass(int a[],int length,int n)
//一趟二路归并排序
{
int i;
for (i = 0; i + 2 * length - 1 < n; i = i + 2 * length) //归并length长的两相邻子表
Merge(a,i,