数据结构与算法分析:第一章: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; ia[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; ia[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; i0; 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.



你可能感兴趣的:(algorithm)