二分搜索和最大子集和

  1. 二分搜索
    #include 
    
    int binary_search(int arr[], int left, int right, int key);
    
    int main()
    {
        int arr[10] = {2, 5, 18, 24, 37, 57, 73, 83, 95, 99};/*输入一个数组,数组默认是已经排序好的*/
        int left, right, key;
        int a;
        left = 0;
        right = 10;
        key = 18;
    
        a = binary_search(arr, left, right, key);/*调用二分搜索函数,并将返回值赋给a*/
        
        printf("%d\n", a);
    
        return 0;
    }
    
    int binary_search(const int arr[], int left, int right, int key)
    {
        if (left > right)
            return -1;
        
        int mid = left + (right - left)/2;
        if (arr[mid] > key)
            return binary_search(arr, left, mid - 1, key);
    
        if (arr[mid] < key)
            return binary_search(arr, mid + 1, right, key);
    
        return mid;
    }
  2. 最大子区间
  3. #include 
    
    int arr[10] = {8, 4, -1, 0, -6, 7, 5, 2, -3, 8};
    
    int main()
    {
        int start = 0;
        int end = 0;
        int max = 0;
        int n = 10;
        int i, j;
        for (i = 0; i < n; i++ )
        {
            int sum = 0;
    	for (j = i; j < n; j++)
    	{
    	    sum = sum + arr[j];
    	    if (sum > max)
    	    {
    	        start = i;
    	        end = j;
     	        max = sum;
                }
            }
        }	
        printf("The max interval arr[%d-%d], and the sum = %d\n", start, end, max);
        return 0;
    }


你可能感兴趣的:(二分搜索和最大子集和)