算法设计与分析 4 估计递归函数复杂度所提及算法

按分治法框架实现二分搜索

int BinarySearch(int A[],int n,int x)
{
	int mid,t;
	if(n<=0)
		return -1;
	else
	{
			mid=n/2;
		if(A[mid]==x)
			return mid;
		else if(x<A[mid])
			return BinarySearch(A,mid,x);//在前一半中搜索
		else
		{
			t=BinarySearch(&A[n+mid+1],n-mid-1,x);//在后一半中搜索
			return (t==-1)?-1:mid+1+t;
		}
	}
}

合并排序(归并排序(二路归并))

#include<stdio.h>
#define MAX 100
int B[MAX];
int MergeSort(int A[],int n){
	//input:A to be sorted,the element number of A is n
	//output:sorted,return 1;
	if(n<=1)
		return 1;
	else{
		MergeSort(A,n/2);//sort from 0 to n/2
		MergeSort(A+n/2,n-n/2);//sort from n/2 to n
		Merge(A,n);//merge
		return 1;
	}
}
int Merge(int A[],int n){
	//input:the first half and the second half has been sorted,the element number is n
	//output:sorted,return 1
	int mid,s1,s2,i,b;
	mid=n/2;//partition:A1[0:mid] and A2[mid:n],both of them are sorted
	s1=0;//head of A1
	s2=mid;//head of A2
	b=0;
	while(s1<mid&&s2<n){//transmit the smaller number from the two sub-Array to B Array respectively
		if(A[s1]<=A[s2]){
			B[b++]=A[s1++];
		}
		else{
			B[b++]=A[s2++];
		}
	}
	if(s1<mid){//transmit the surplus element of the former sub-Array to B Array
		for(i=s1;i<mid;i++){
			B[b++]=A[i];
		}
	}
	else{//transmit the surplus element of the other sub-Array to B Array
		for(i=s2;i<n;i++){
			B[b++]=A[i];
		}
	}
	for(i=0;i<n;i++){//depulicate B Array to A Array
		A[i]=B[i];
	}
	return 1;
}

快速排序算法

#include<stdio.h>
int QuickSort(int A[],int n)
{
	int p;
	if(n<=1)
	{
		return 1;
	}
	else
	{
		p=Partition(A,n);
		QuickSort(A,p);
		QuickSort(A+p+1,n-p-1);
		return 1;
	}
}

int Partition(int A[],int n)
{
	int low,high,x,p,i;
	p=A[0];//记录主元pivot(也称枢轴)
	x=0;//空位置
	low=0;//低指针
	high=n-1;//高指针
	while(low<high){//指针从两头相对扫描,直到相遇
		while(low<high&&A[high]>p)//从后向前寻找比主元p小的元素
			high--;
		if(low<high){
			A[x]=A[high];
			x=high;
		}
		while(low<high&&A[low]<=p)//从前向后寻找比主元p大的元素
			low++;
		if(low<high){
			A[x]=A[low];
			x=low;
		}
	}
	A[x]=p;
	return x;
}

随机选主元的快速排序

#include<stdio.h>
#include<stdlib.h>
int QuickSort(int A[],int n)
{
	int p;
	if(n<=1)
	{
		return 1;
	}
	else
	{
		p=Partition(A,n);
		QuickSort(A,p);
		QuickSort(A+p+1,n-p-1);
		return 1;
	}
}

int Partition(int A[],int n)
{
	int low,high,x,p,i;
	x=1.0*rand()/RAND_MAX*n;//随机挑选的主元位置
	p=A[x];//记录主元pivot(也称枢轴)
	A[x]=A[0];
	x=0;
	low=0;//低指针
	high=n-1;//高指针
	while(low<high){//指针从两头相对扫描,直到相遇
		while(low<high&&A[high]>p)//从后向前寻找比主元p小的元素
			high--;
		if(low<high){
			A[x]=A[high];
			x=high;
		}
		while(low<high&&A[low]<=p)//从前向后寻找比主元p大的元素
			low++;
		if(low<high){
			A[x]=A[low];
			x=low;
		}
	}
	A[x]=p;
	return x;
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值