Answered step by step
Verified Expert Solution
Question
1 Approved Answer
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.
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
Step: 1
Get Instant Access to Expert-Tailored Solutions
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started