• Status: Solved
• Priority: Medium
• Security: Public
• Views: 240

# I want implement This algorithm and change it to Iterative

i want java or c# or vb language
i will evaluate any help.
('<---' is same as '=')
Algorithm name: MAJORITY
Input: Array A where the elements from 1 to n
output: The majority element if it is exist; otherwise none

---
c<---candidate(1)
count<--- 0
for j <--- 1 to n
if A[j] ==c then count<--count+1
end if
end for
if count > n/2 then return c {note: The n is integer and n/2 also}
else return none
end if

---
procedure candidate(m)
j <-- m; c <-- A[m];count <-- 1
while j<n and count>0
j<-- j+1
if A[j] = c then count<-- count+1
else count<-- count -1
end while
if j==n then return c
else return candidate(j+1)

-----------

remember i want the same algorithm in the iteration method
0
st214387
• 2
1 Solution

Commented:
Well, I'm not sure what you are trying to do with this but here is a line by line translation. You need to the array into the second function if you don't have it declared in a higher context. Here is a VB "solution," I haven't tested it but it looks to be a direct translation:

Public Function firstProc(ByVal a() As Integer) As Integer
Dim c As Integer = candidate(1, a)
Dim i As Integer
Dim count As Integer = 0
For i = 0 To a.Length
If a(i) = c Then
count += 1
End If
Next

If count > (a.Length / 2) Then
Return count
Else
Return -1
End If
End Function

Public Function candidate(ByVal m As Integer, ByVal a() As Integer) As Integer
Dim j As Integer = m
Dim c As Integer = a(m)
Dim count As Integer = 1
While (j < a.Length) And (count > 0)
j += 1
If a(j) = c Then
count += 1
Else
count = -1
End If
End While

If j = a.Length Then
Return c
Else
Return candidate((j + 1), a)
End If
End Function
0

Author Commented:
i will wait until other answers
0

Commented:
Does this not work for you?
0

## Featured Post

• 2
Tackle projects and never again get stuck behind a technical roadblock.