oral_quiz->#旋转数组中找最小值#

#include <stdio.h>
#include <exception>

int MinInOrder(int* numbers, int start, int end) {
	int result = numbers[start];
	for(int i=start+1; i<=end; ++i) {
		if(result > numbers[i]) result = numbers[i];
	}
	return result;
}

int MyMinNumberInRotatedArray(int* array, int start, int end) {
	if(array == NULL || start < 0 || end < start)
		throw std::exception();

	//no rotated numbers
	if(array[end] >= array[start]) {
		return array[start];
	}

	while(end > start && end != start + 1) {
		int newPos = (start + end) / 2;
		if(array[newPos] >= array[start]) start = newPos;
		if(array[newPos] <= array[end]) end = newPos;
	}
	return array[end];
}

int Min(int* numbers, int length) {
	if(numbers == NULL || length <= 0)
		throw std::exception();

	int start = 0;
	int end = length - 1;
	int index = start;
	while(numbers[start] >= numbers[end]) {
		if(1 == end - start) {
			index = end; break;
		}
		index = (start + end) / 2;

		if(numbers[start] == numbers[end] && numbers[start] == numbers[index])
			return MinInOrder(numbers, start, end);

		if(numbers[index] >= numbers[start]) start = index;
		if(numbers[index] <= numbers[end]) end = index;
	}

	return numbers[index];
}

//=============================Test============================
void Test(const char* testName, int* array, int length, int expected) {
	if(testName != NULL) printf("%s begins:\n", testName);

//	printf("minimum number is %d\n", MyMinNumberInRotatedArray(array, start, end));
	try{
//		int min = MyMinNumberInRotatedArray(array, start, end);
		int min = Min(array, length);
		if(expected == min) {
			printf("%s passed.\n", testName);
		}
		else {
			printf("%s failed.\n", testName);
		}
	} catch (std::exception& e) {
		printf("Invalid parameters");
	}

}

//normal array
void Test1() {
	const int length = 5;
	int array[length] = {3,4,5,1,2};
	Test("Test1", array, 5, 1);
}

//same first half
void Test2() {
	const int length = 5;
	int array[length] = {3,3,3,1,2};
	Test("Test2", array, 5, 1);
}

//same second half
void Test3() {
	const int length = 5;
	int array[length] = {3,4,5,1,1};
	Test("Test3", array, 5, 1);
}

//only two numbers && no rotated numbers
void Test4() {
	const int length = 2;
	int array[length] = {3,4};
	Test("Test4", array, 2, 3);
}

//only one number
void Test5() {
	const int length = 1;
	int array[length] = {3};
	Test("Test5", array, 1, 3);
}

//normal array && no rotated numbers
void Test6() {
	const int length = 5;
	int array[length] = {5,7,13,15,20};
	Test("Test6", array, 5, 5);
}

//invalid parameters
void Test7() {
	const int length = 3;
	int array[length] = {0};
	Test("Test7", NULL, 6, 9);
}

int main(int argc, char* argv[]) {
	Test1();
	Test2();
	Test3();
	Test4();
	Test5();
	Test6();
	Test7();
	return 0;
}



你可能感兴趣的:(旋转数组)