數據結構與算法分析:第一章:Finding the kth largest number and The four basic rules of recursion

查找第K個最大值的兩種方法;遞歸的四條基本法則。

書中首先介紹了兩種簡單的方法:

One way to solve this problem would be to read the n numbers into an array, sort the array in decreasing order by some simple algorithm such as bubble sort, and then return the element in position k.

int find_kth_largest_num(int *a, int num, int k)
{
	int exchange = 0;
	for(int i = 0; i<num-1; i++)
	{
		exchange = 0;
		for(int j = 0; j<num-1-i; j++)
		{
			if(a[j]>a[j+1])
			{
				int tmp = a[j];
				a[j]=a[j+1];
				a[j+1]=tmp;
				exchange = 1;
			}
		}
		if(0 == exchange)
		{
			break;
		}
	}
	return a[k-1];
}

A somewhat better algorithm might be to read the first k elements into an array and sort them (in decreasing order).Next, each remaining element is read one by one. As a new element arrives, it is ignored if it is smaller than the kth element in the array. Otherwise, it is placed in its correct spot in the array, bumping one

int find_kth_largest_num_2(int *a, int num, int k)
{
	//sort the first k elements
	int exchange = 0;
	for(int i = 0; i<k-1; i++)
	{
		exchange = 0;
		for(int j = 0; j<k-1-i; j++)
		{
			if(a[j]>a[j+1])
			{
				int tmp = a[j];
				a[j]=a[j+1];
				a[j+1]=tmp;
				exchange = 1;
			}
		}
		if(0 == exchange)
		{
			break;
		}
	}

	//As a new element arrives, it is ignored if it is smaller than the kthelement in the array. 
	//Otherwise, it is placed in its correct spot in the array, bumping one element out of the array.
	for(int i = 0; i<num-k; i++)
	{
		//Get the next (num-k) number in order; Then put the number in the (k+1)th position
		a[k] = a[k+i];
		for(int j = k; j>0; j--)  // sort the (k+1) num
		{
			if(a[j]>a[j-1])
			{
				int tmp = a[j];
				a[j] = a[j-1];
				a[j-1] = tmp;
			}
			else
			{
				break;
			}
		}
	}

	return a[k-1];
}


遞歸的四條基本法則:

When writing recursive routines, it is crucial to keep in mind the four basic rules of recursion:

1. Base cases.You must always have some base cases, which can be solved without recursion.

2. Making progress. For the cases that are to be solved recursively, the recursive call must always be to a case that makes progress toward a base case.

3. Design rule.Assume that all the recursive calls work.

4. Compound interest rule. Never duplicate work by solving the same instance of a problem in separate recursive calls.



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章