求最大连续子数组

 1 //寻找整型数组的最大连续子数组,并输出起止位  2 //加上一个数使子数组变大,减去一个数使子数组变小  3 //遍历过程中,如果中间变量tmp为负时,则丢弃已经遍历的和

 4 int MaxSubArray(int data[], int size, size_t &beg, size_t &end)  5 {  6     int tmp = 0;  7     int maxvalue = 0;  8     size_t tmp_beg = 0;  9     for(size_t i=0; i<size; i++) 10  { 11         tmp += data[i]; 12         if (tmp < 0)//如果小于0,则起始位变为i+1,负数情况暂且不考虑

13  { 14             tmp = 0; 15             tmp_beg = i + 1; 16  } 17         if (tmp > maxvalue)//如果更新后的值变大,则更新maxvalue与终止位end与起始位beg

18  { 19             maxvalue = tmp; 20             end = i; 21             if (tmp_beg <= end) 22  { 23                 beg = tmp_beg; 24  } 25  } 26  } 27     //全负数的情况

28     if (maxvalue == 0) 29  { 30         maxvalue = data[0]; 31         for (size_t j = 0; j < size; j++) 32  { 33             if (data[j] > maxvalue) 34  { 35                 maxvalue = data[j]; 36                 beg = end = j; 37  } 38  } 39  } 40     return maxvalue; 41 }


下面是测试函数:

 1 void testMaxSubArray()  2 {  3     //求数组中连续的最大数,并输出起止位

 4     int data[] = {-1, 98, 8, 76, -23, -988, 22, 12, 32, 48, 23, 23 ,23, -8 -987};  5     int data1[] = {1, 2, -2, 1};  6     size_t beg = 0;  7     size_t end = 0;  8     cout << MaxSubArray(data1, sizeof(data1)/sizeof(data1[0]), beg, end) << endl;  9     if (beg == end) 10  { 11         cout << beg << endl; 12  } 13     else

14  { 15         cout << beg << " " << end << endl; 16  } 17 }

 

 

你可能感兴趣的:(数组)