Question: Give an iterative version of Algorithm majority. Input: An array A[1..n] of n elements. Output: The majority element if it exists; otherwise none. 1. cleftarrow
Give an iterative version of Algorithm majority.![Give an iterative version of Algorithm majority. Input: An array A[1..n] of](https://dsd5zvtm8ll6.cloudfront.net/si.experts.images/questions/2024/09/66f52c0aeec03_62666f52c0a7459d.jpg)
Input: An array A[1..n] of n elements. Output: The majority element if it exists; otherwise none. 1. cleftarrow candidate(1) 2. count leftarrow 0 3. for j leftarrow 1 to n 4. if A[j] = c then counts leftarrow count + 1 5. end for 6. if count > |n/2| then return c 7. else return none Procedure candidate(m) 1. j leftarrow m; c leftarrow A[m]; count leftarrow 1 2. while j 0 3. j leftarrow j + 1 4. if A[j] = c then counts leftarrow count + 1 5. else counts leftarrow count - 1 6. end while 7. if j = n then return c {See Exercises 5.31 and 5.32.} 8. else return candidate(j + 1) Input: An array A[1..n] of n elements. Output: The majority element if it exists; otherwise none. 1. cleftarrow candidate(1) 2. count leftarrow 0 3. for j leftarrow 1 to n 4. if A[j] = c then counts leftarrow count + 1 5. end for 6. if count > |n/2| then return c 7. else return none Procedure candidate(m) 1. j leftarrow m; c leftarrow A[m]; count leftarrow 1 2. while j 0 3. j leftarrow j + 1 4. if A[j] = c then counts leftarrow count + 1 5. else counts leftarrow count - 1 6. end while 7. if j = n then return c {See Exercises 5.31 and 5.32.} 8. else return candidate(j + 1)
Step by Step Solution
There are 3 Steps involved in it
Get step-by-step solutions from verified subject matter experts
