The Program of Algorithms ------- Diveide and Conquer ---- Quicksort

Divide and Conquer:

  1. Divide: Partition array into 2 subarrays around pivot, such that elements in lower subarray little than  pivot, and upper subarray bigger than pivot.

  2. Conquer: Recursively sort the two subarrays.

  3. Combine: Trivial.

 

Randomized QuickSort:

   Idea: 1. Pivot is an random element in the array.

            2. Random the Sequence of the arry.

   Realize the idea1 --- CPP:

int PartitionArr(int* Arr,int p,int q){
	srand((unsigned)time(NULL));
	int size=q-p+1;
	int index=rand()%(size)+p;
	int pivot=Arr[index];
	Arr[index]=Arr[p];
	Arr[p]=pivot;
	int i=p;
	
	for(int j=p+1;j<p+size;j++){
		if(Arr[j]<=pivot){
			i++;
			int tmp=Arr[i];
			Arr[i]=Arr[j];
			Arr[j]=tmp;
		}
	}	
	
	int tmp=Arr[i];
	Arr[i]=Arr[p];
	Arr[p]=tmp;
	return i;
}

void QuickSort(int* Arr,int p,int q){
	if(p<q){
		int r=PartitionArr(Arr,p,q);
		QuickSort(Arr,p,r-1);
		QuickSort(Arr,r+1,q);
	}
}

 

The importance of the randomized algorithm is not about the realization but understand the average Time Cost is O(nlgn). It reference to the knowledge about Probability.

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值