Question: Give an iterative version of Algorithm majority MAJORITY Input: An array >A[l..n] of n elements. Output: The majority element if it exists; otherwise none. C
Give an iterative version of Algorithm majority
![Give an iterative version of Algorithm majority MAJORITY Input: An array >A[l..n]](https://dsd5zvtm8ll6.cloudfront.net/si.experts.images/questions/2024/09/66f547c92d91a_72866f547c8c6820.jpg)
MAJORITY Input: An array >A[l..n] of n elements. Output: The majority element if it exists; otherwise none. C left arrow candidate(l) count left arrow 0 for j left arrow 1 to n if.A[j] = c then count left arrow- count + 1 end for if count > [n/2] then return c else return none Procedure candidate(m) j left arrow m; c left arrow A[m]; count left arrow 1 while j 0 j left arrow j + 1 if.A[j] = c then counts left arrow count + 1 else count left arrow count - 1 end while if j = n then return c {See Exercises 5.31 and 5.32.} else return candidate(j + 1) MAJORITY Input: An array >A[l..n] of n elements. Output: The majority element if it exists; otherwise none. C left arrow candidate(l) count left arrow 0 for j left arrow 1 to n if.A[j] = c then count left arrow- count + 1 end for if count > [n/2] then return c else return none Procedure candidate(m) j left arrow m; c left arrow A[m]; count left arrow 1 while j 0 j left arrow j + 1 if.A[j] = c then counts left arrow count + 1 else count left arrow count - 1 end while if j = n then return c {See Exercises 5.31 and 5.32.} 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
