旋转数组的最小值输出

//CSDN学员视频学习数据结构算法示例代码

//旋转数组   {1, 2, 3, 4, 5}

//旋转数组  {3, 4, 5, 1, 2}  局部是按顺序排列的

#include "stdafx.h"
#include <stdlib.h>
#include <exception>//错误判断

int MinInOrder(int * numbers, int index1, int index2);

int Min(int *numbers, int length)
{
	if (numbers == NULL || length <= 0)
	{
		throw new std::exception("Invalid parameters");
	}
	int index1 = 0;//第一个
	int index2 = length - 1;//最后一个
	int indexMid = index1;//中间赋值

	while(numbers[index1] >= numbers[index2])
	{
		if (index2 - index1 == 1)//找到这个最小值.退出
		{
			indexMid = index2;
			break;
		}
		indexMid = (index1 + index2) / 2;
		if (numbers[index1] == numbers[index2] && numbers[indexMid] == numbers[index1])//两个相等 并且 中间的也和第一个相等
		{
			//特殊处理的函数
			return MinInOrder(numbers, index1, index2);
		}
		if (numbers[indexMid] >= numbers[index1])
		{
			index1 = indexMid;//中间值赋值给第一个元素
		}
		else if (numbers[indexMid] <= numbers[index2])
		{
			index2 = indexMid;
		}
	}
	return numbers[indexMid];
}

//特殊情况强制比较最小值
int MinInOrder(int *number, int index1, int index2)
{
	int result = number[index1];
	for (int i = index1 + 1; i <= index2; ++i)
	{
		if (result > number[i])
		{
			result = number[i];
		}
	}
	return result;
}

void Test(int *number, int length, int execpted)
{
	int result = 0;
	try
	{
		result = Min(number, length);
		for (int i = 0; i< length; ++i)
		{
			printf("%d ", number[i]);
		}
		if (result == execpted)
		{
			printf("\tpassed\n");
		}
		else
		{
			printf("\tfailed\n");
		}
	}
	catch (...)
	{
		if (number == NULL)
		{
			printf("\tpassed.\n");
		}
		else
			printf("\tfailed\n");
	}
}

int _tmain(int argc, _TCHAR* argv[])
{
	int array0[] = {1, 2, 3, 4, 5};
	Test(array0, sizeof(array0)/ sizeof(int), 1);

	//int array1[] = {3, 4, 5, 1, 2};
	//Test(array1, sizeof(array1)/ sizeof(int), 1);

	//int array2[] = {3, 4, 5, 1, 2, 2};
	//Test(array2, sizeof(array2)/ sizeof(int), 1);

	//int array3[] = {1, 0, 1, 1, 1};
	//Test(array3, sizeof(array3)/ sizeof(int), 0);

	//int array4[] = {1};
	//Test(array4, sizeof(array4)/ sizeof(int), 1);

//	int array10[] = {5, 1, 2, 3, 4};
//	Test(array10, sizeof(array10)/ sizeof(int), 1);

	Test(NULL, 0, 0);
	system("pause");
	return 0;
}


你可能感兴趣的:(旋转数组的最小值输出)