long int max_subarray(int array[], int *low, int *high)
{
    long int max_crossing_subarray(int array[], int *low, int mid, int *high);
    if (*low == *high) {
        return array[*low];
    } else {
        //Don't change avoids overflow
        int mid = *low + (*high - *low)/2;

        int left_low = *low;
        int left_high = mid;
        long int left_sum = max_subarray(array, &left_low, &left_high);

        int right_low = mid + 1;
        int right_high = *high;
        long int right_sum = max_subarray(array, &right_low, &right_high);

        int cross_low = *low;
        int cross_high = *high;
        long int cross_sum = max_crossing_subarray(array, &cross_low, mid, &cross_high);

        if (left_sum >= right_sum && left_sum >= cross_sum)
        {
            *low = left_low;
            *high = left_high;
            return left_sum;

        } else if (right_sum >= left_sum && right_sum >= cross_sum) {
            *low = right_low;
            *high = right_high;
            return right_sum;

        } else {
            *low = cross_low;
            *high = cross_high;
            return cross_sum;
        }
    }
}
Exemplo n.º 2
0
/*
  Calculates maximum sub-array of a given array by Divide & Conquer.

  Takes 3 arguments
  - int *arr: pointer to an int array
  - int start: index of the int array *arr to start from
  - int end: index of the int array *arr to end at

  Returns: SubArray *sub_array
*/
SubArray *max_subarray_dq(int *arr, int start, int end)
{
    check(arr, "max_subarray_dq() was passed a NULL array.");
    check(start >= 0 && end >= 0,
          "max_subarray_dq() was passed invalid indexes (%d, %d)",
          start, end);

    if(start == end) {
        SubArray *sub_array = malloc(sizeof (SubArray));
        sub_array->arr = arr;
        sub_array->start = start;
        sub_array->end = end;
        sub_array->sum = arr[start];
        return sub_array;
    }

    int mid = start + ((end - start)
                       / 2);
    SubArray *max_left = max_subarray_dq(arr, start, mid);
    SubArray *max_right = max_subarray_dq(arr, mid + 1, end);
    SubArray *max_crossing = max_crossing_subarray(arr, start, mid, end);

    if(max_left->sum > max_right->sum) {
        if(max_left->sum > max_crossing->sum) {
            return max_left;
        } else {
            return max_crossing;
        }
    } else {
        if(max_right->sum > max_crossing->sum) {
            return max_right;
        } else {
            return max_crossing;
        }
    }
error:
    return NULL;
}