zoukankan      html  css  js  c++  java
  • 一些简单小算法

    二分查找

    #include <iostream>
    
    using namespace std;
    
    //非递归实现
    int BinarySearch(int array[], int len, int value)
    {
    	if (array == NULL || len <= 0)
    		return -1;
    
    	int low = 0;
    	int high = len - 1;
    	while (low <= high)
    	{
    		int mid = low + (high - low) / 2;
    		if (array[mid] == value)
    			return mid;
    		else if (array[mid] > value)
    			high = mid - 1;
    		else
    			low = mid + 1;
    	}
    
    	return -1;
    }
    //递归实现
    int BinarySearch_Recursive(int array[], int low, int high, int value)
    {
    	if (low > high)
    		return -1;
    	int mid = low + (high - low) / 2;
    	if (array[mid] == value)
    		return mid;
    	else if (array[mid] > value)
    		return BinarySearch_Recursive(array, low, mid - 1, value);
    	else
    		return BinarySearch_Recursive(array, mid + 1, high, value);
    
    }
    
    int main(int argc, char *argv[])
    {
    	int i, j;
    	int arr[10];
    	for (i = 0; i < 10; i++)
    	{
    		arr[i] = i * 2;
    	}
    	cout << "Input the search number:";
    	cin >> j;
    	int location = BinarySearch(arr, 10, j);
    	if (location != -1)
    		cout << "Exist1:" << location << endl;
    	else
    		cout << "Not existed in array!" << endl;
    	location = BinarySearch_Recursive(arr, 0, 9, j);
    	if (location != -1)
    		cout << "Exist2:" << location << endl;
    	else
    		cout << "Not existed in array!" << endl;
    	system("pause");
    	return 0;
    }
    

    最大子段和

    #include <iostream>
    
    using namespace std;
    
    //b[j] = max{b[j-1]+a[j], a[j]}  0 =< j < n
    int MaxSum(int n, int* a)
    {
    	int sum = 0, b = 0;
    	for (int i = 0; i < n; i++)
    	{
    		if (b > 0)
    		{
    			b += a[i];
    		}
    		else
    		{
    			b = a[i];
    		}
    		if (b > sum)
    		{
    			sum = b;
    		}
    	}
    	return sum;
    }
    
    int main()
    {
    	int a[10] = { 1, -8, 3, -4, 5, 7, 5, 1, -2, 9 };
    	int res = MaxSum(10, a);
    	cout << res << endl;
    	system("pause");
    	return 0;
    }
    
    感谢阅读,如有问题,请批评指正,谢谢。
  • 相关阅读:
    wordpress自定义文章类型public参数说明
    wordpress自定义文章类型描述信息description的使用
    wordpress进阶教程(二):注册一个自定义的文章类型
    wordpress进阶教程(一):wordpress文章类型
    wodpress进阶教程:前言
    Lucene全文检索基础
    MongoDB实用教程
    1小时学会JQuery
    Ajax+Struts2实现验证码验证功能
    AJAX编程实践
  • 原文地址:https://www.cnblogs.com/clwsec/p/11552748.html
Copyright © 2011-2022 走看看