Skip to content

Commit 5ad5d0a

Browse files
Merge pull request #253 from Dipit12/main
feat: added code for Moore voting algorithm in java
2 parents 150c534 + 3d22895 commit 5ad5d0a

2 files changed

Lines changed: 84 additions & 0 deletions

File tree

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
public class MooreVoting {
2+
3+
public static Integer findMajorityElement(int[] nums) {
4+
// Phase 1: Find candidate
5+
int candidate = 0, count = 0;
6+
7+
for (int num : nums) {
8+
if (count == 0) {
9+
candidate = num;
10+
}
11+
if (num == candidate) {
12+
count++;
13+
} else {
14+
count--;
15+
}
16+
}
17+
18+
// Phase 2: Verify candidate
19+
count = 0;
20+
for (int num : nums) {
21+
if (num == candidate) {
22+
count++;
23+
}
24+
}
25+
26+
if (count > nums.length / 2) {
27+
return candidate;
28+
} else {
29+
return null; // No majority element
30+
}
31+
}
32+
33+
public static void main(String[] args) {
34+
int[] nums = {2, 2, 1, 1, 2, 2, 2};
35+
Integer majority = findMajorityElement(nums);
36+
37+
if (majority != null) {
38+
System.out.println("Majority Element: " + majority);
39+
} else {
40+
System.out.println("No Majority Element exists");
41+
}
42+
}
43+
}
Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
public class DutchFlag {
2+
3+
public static void sortColors(int[] nums) {
4+
int low = 0, mid = 0, high = nums.length - 1;
5+
6+
while (mid <= high) {
7+
switch (nums[mid]) {
8+
case 0:
9+
// swap nums[low] and nums[mid]
10+
int temp0 = nums[low];
11+
nums[low] = nums[mid];
12+
nums[mid] = temp0;
13+
low++;
14+
mid++;
15+
break;
16+
17+
case 1:
18+
mid++;
19+
break;
20+
21+
case 2:
22+
// swap nums[mid] and nums[high]
23+
int temp2 = nums[mid];
24+
nums[mid] = nums[high];
25+
nums[high] = temp2;
26+
high--;
27+
break;
28+
}
29+
}
30+
}
31+
32+
public static void main(String[] args) {
33+
int[] nums = {2, 0, 2, 1, 1, 0};
34+
sortColors(nums);
35+
36+
System.out.print("Sorted array: ");
37+
for (int num : nums) {
38+
System.out.print(num + " ");
39+
}
40+
}
41+
}

0 commit comments

Comments
 (0)