RetValue FIND_MAXIMUM_SUBARRAY(int* A, int low, int high) { RetValue ret; if(high == low) { // 1 ret.max_left = low; ret.max_right = high; ret.sum = A[low]; #ifdef DEBUG printRet(ret); #endif return ret; // 2 base case: only one element } else { int mid = (low + high) / 2; // 3 #ifdef DEBUG printf("FIND_MAXIMUM_SUBARRAY(low: %d, mid: %d)\n", low, mid); #endif RetValue leftRet = FIND_MAXIMUM_SUBARRAY(A, low, mid); // 4 #ifdef DEBUG printf("FIND_MAXIMUM_SUBARRAY(mid+1: %d, high: %d)\n", mid+1, high); #endif RetValue rightRet = FIND_MAXIMUM_SUBARRAY(A, mid + 1, high); // 5 #ifdef DEBUG printf("FIND_MAX_CROSSING_SUBARRAY(low: %d, mid: %d, high: %d)\n", low, mid, high); #endif RetValue crossRet = FIND_MAX_CROSSING_SUBARRAY(A, low, mid, high); //6 #ifdef DEBUG printf("leftRet ");printRet(leftRet); printf("rightRet ");printRet(rightRet); printf("crossRet ");printRet(crossRet); #endif if (leftRet.sum >= rightRet.sum && leftRet.sum >= crossRet.sum){ // 7 #ifdef DEBUG printf("Choose left\n"); #endif return leftRet; // 8 } else if (rightRet.sum >= leftRet.sum && rightRet.sum >= crossRet.sum){ // 9 #ifdef DEBUG printf("Choose right\n"); #endif return rightRet; // 10 } else { #ifdef DEBUG printf("Choose cross\n"); #endif return crossRet; // 11 } } }
node* FIND_MAXIMUM_SUBARRAY(int* A,int low , int high) { node* n; n=(node* )malloc(sizeof(node)*1); if(low==high) { //printf("%d",A[0]); n->data=A[low]; n->high=high; n->low=low; return n; } int mid=(high+low)/2; node* left=FIND_MAXIMUM_SUBARRAY(A,low,mid); node* right=FIND_MAXIMUM_SUBARRAY(A,mid+1,high); node mide=FIND_MAX_CROSSING_SUBARRAY(A,low ,mid, high); if(left->data>=right->data) { n->data=left->data; n->high=left->high; n->low=left->low; } else if(right->data>=mide.data) { n->data=right->data; n->high=right->high; n->low=right->low; } else { n->data=mide.data; n->high=mide.high; n->low=mide.low; } return n; }