DS02_Ch02b - 3 Compare the Algorithms Example Given...

Info iconThis preview shows pages 1–4. Sign up to view the full content.

View Full Document Right Arrow Icon
§3 Compare the Algorithms 〖 Example 〖 Given (possibly negative) integers A 1 , A 2 , …, A N , find the maximum value of . = j i k k A Max sum is 0 if all the integers are negative. Algorithm 1 int MaxSubsequenceSum ( const int A[ ], int N ) { int ThisSum, MaxSum, i, j, k; /* 1*/ MaxSum = 0; /* initialize the maximum sum */ /* 2*/ for ( i = 0; i < N; i++ ) /* start from A[ i ] */ /* 3*/ for ( j = i; j < N; j++ ) { /* end at A[ j ] */ /* 4*/ ThisSum = 0; /* 5*/ for ( k = i; k <= j; k++ ) /* 6*/ ThisSum += A[ k ]; /* sum from A[ i ] to A[ j ] */ /* 7*/ if ( ThisSum > MaxSum ) /* 8*/ MaxSum = ThisSum; /* update max sum */ } /* end for-j and for-i */ /* 9*/ return MaxSum; } T ( N ) = O( N 3 ) Detailed analysis is given on p.18- 19. 1/9
Background image of page 1

Info iconThis preview has intentionally blurred sections. Sign up to view the full version.

View Full DocumentRight Arrow Icon
Algorithm 2 §3 Compare the Algorithms int MaxSubsequenceSum ( const int A[ ], int N ) { int ThisSum, MaxSum, i, j; /* 1*/ MaxSum = 0; /* initialize the maximum sum */ /* 2*/ for ( i = 0; i < N; i++ ) { /* start from A[ i ] */ /* 3*/ ThisSum = 0; /* 4*/ for ( j = i; j < N; j++ ) { /* end at A[ j ] */ /* 5*/ ThisSum += A[ j ]; /* sum from A[ i ] to A[ j ] */ /* 6*/ if ( ThisSum > MaxSum ) /* 7*/ MaxSum = ThisSum; /* update max sum */ } /* end for-j */ } /* end for-i */ /* 8*/ return MaxSum; } T ( N ) = O( N 2 ) 2/9
Background image of page 2
§3 Compare the Algorithms Algorithm 3 Divide and Conquer 4 - 3 5 - 2 - 1 2 6 - 2 conquer divide 4 5 6 2 6 8 11
Background image of page 3

Info iconThis preview has intentionally blurred sections. Sign up to view the full version.

View Full DocumentRight Arrow Icon
Image of page 4
This is the end of the preview. Sign up to access the rest of the document.

This note was uploaded on 10/20/2011 for the course COMPUTER S 10586 taught by Professor Jilinwang during the Spring '09 term at Zhejiang University.

Page1 / 9

DS02_Ch02b - 3 Compare the Algorithms Example Given...

This preview shows document pages 1 - 4. Sign up to view the full document.

View Full Document Right Arrow Icon
Ask a homework question - tutors are online