REPLACEMENT SELECTION SORT: - java

I am working on Replacement Selection sort project but i keep getting the error Exception in thread main Java.lang.ArrayIndexOutOfBoundsException:10 at ReplacementSelection.swap(ReplacementSelection.java:42) at ReplacementSelection.siftDown(ReplacementSelection.java:69) at Replacement..
class ReplacementSelection {
static int[] array = new int[]{ 1,2,3,4,5,6,7,8,9,10 };
public static void sort() {
System.out.println("before:" + Arrays.toString(array));
for (int i = array.length/2; i >= 0; i--) {
siftDown(i);
}
int count = array.length-1;
while (count > 0)
{
swap(array[0], array[count]);
--count;
siftDown(0);
}
System.out.println("after:" + Arrays.toString(array));
}
public static void swap(int i, int j)
{
int tmp;
tmp = array[i];
array[i] = array[j];
array[j] = tmp;
}
public static void siftDown(int index)
{
int count = array.length;
// Left child is at index*2+1. Right child is at index*2+2;
while (true)
{
// first find the largest child
int largestChild = index*2+1;
// if left child is larger than count, then done
if (largestChild >= count)
{
break;
}
// compare with right child
if (largestChild+1 < count && array[largestChild] < array[largestChild+1])
{
++largestChild;
}
// If item is smaller than the largest child, then swap and continue.
if (array[index] < array[largestChild])
{
swap(array[index], array[largestChild]);
index = largestChild;
}
else
{
break;
}
}
}
public static void main(String[] args){
ReplacementSelection a = new ReplacementSelection();
a.sort();
}
}

You have written a swap method which takes indices as arguments. However, you pass it the values in the array at those indices instead of the indices themselves:
swap(array[0], array[count]);
and
swap(array[index], array[largestChild]);
To fix the exception error just pass the indices to the method:
swap(0, count);
and
swap(index, largestChild);

As #Pajacar123 mentioned, you should learn to use debugger.
In line
swap(array[index], array[largestChild]);
You are passing value from array which is at last index of table(index 9 value 10). Then when in method sawp in line array[i] = array[j];
j value is 10 while max index of table is 9. That causes exception. You are trying to refer to not existing elemnt.

Related

ArrayList<ArrayList<Integer> returns same values when adding different elements to it

I need to add List of permutation to ArrayList type but for me when I try to run below code then I am getting same value repeated. Please help me here.
public static void permutation(ArrayList<Integer> perm, ArrayList<ArrayList<Integer>> solution, int index) {
if (index >= perm.size()) {
solution.add(perm);
return;
}
for (int i = index; i < perm.size(); i++) {
Collections.swap(perm, index, i);
permutation(perm, solution, index + 1);
Collections.swap(perm, index, i);
}
}
if passed [1,2,3] as first argument.
Expected output: [[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]] should be added to second argument.
Actual output: [[1,2,3],[1,2,3],[1,2,3],[1,2,3],[1,2,3],[1,2,3]]
You need to understand that
solution.add(perm);
does not add a copy of perm to solution - it only adds a reference to perm. You are changing the contents perm after that line, which means that whatever seems to have been added to solution also changes (because it is the same object).
What you need to do instead is to add a copy of perm to the solution.
In your case the simplest way to create such a copy is by creating a new ArrayList<Integer>(perm):
solution.add(new ArrayList<Integer>(perm));
public class GetAllPermutations {
public static void getPermutations(int[] array){
helper(array, 0);
}
private static void helper(int[] array, int pos){
if(pos >= array.length - 1){
System.out.print("[");
for(int i = 0; i < array.length - 1; i++){
System.out.print(array[i] + ", ");
}
if(array.length > 0)
System.out.print(array[array.length - 1]);
System.out.println("]");
return;
}
for(int i = pos; i < array.length; i++){
int t = array[pos];
array[pos] = array[i];
array[i] = t;
helper(array, pos+1);
t = array[pos];
array[pos] = array[i];
array[i] = t;
}
}
public static void main(String args[]) {
int[] numbers = {1, 2, 3};
getPermutations(numbers);
}
}

Finding non duplicate element in an array

I am stuck in the following program:
I have an input integer array which has only one non duplicate number, say {1,1,3,2,3}. The output should show the non duplicate element i.e. 2.
So far I did the following:
public class Solution {
public int singleNumber(int[] arr){
int size = arr.length;
int temp = 0;
int result = 0;
boolean flag = true;
int[] arr1 = new int[size];
for(int i=0;i<size;i++){
temp = arr[i];
for(int j=0;j<size;j++){
if(temp == arr[j]){
if(i != j)
//System.out.println("Match found for "+temp);
flag = false;
break;
}
}
}
return result;
}
public static void main(String[] args) {
int[] a = {1,1,3,2,3};
Solution sol = new Solution();
System.out.println("SINGLE NUMBER : "+sol.singleNumber(a));
}
}
Restricting the solution in array is preferable. Avoid using collections,maps.
public class NonRepeatingElement {
public static void main(String[] args) {
int result =0;
int []arr={3,4,5,3,4,5,6};
for(int i:arr)
{
result ^=i;
}
System.out.println("Result is "+result);
}
}
Since this is almost certainly a learning exercise, and because you are very close to completing it right, here are the things that you need to change to make it work:
Move the declaration of flag inside the outer loop - the flag needs to be set to true every iteration of the outer loop, and it is not used anywhere outside the outer loop.
Check the flag when the inner loop completes - if the flag remains true, you have found a unique number; return it.
From Above here is the none duplicated example in Apple swift 2.0
func noneDuplicated(){
let arr = [1,4,3,7,3]
let size = arr.count
var temp = 0
for i in 0..<size{
var flag = true
temp = arr[i]
for j in 0..<size{
if(temp == arr[j]){
if(i != j){
flag = false
break
}
}
}
if(flag == true){
print(temp + " ,")
}
}
}
// output : 1 , 4 ,7
// this will print each none duplicated
/// for duplicate array
static void duplicateItem(int[] a){
/*
You can sort the array before you compare
*/
int temp =0;
for(int i=0; i<a.length;i++){
for(int j=0; j<a.length;j++){
if(a[i]<a[j]){
temp = a[i];
a[i] = a[j];
a[j] = temp;
}
}
}
int count=0;
for(int j=0;j<a.length;j++) {
for(int k =j+1;k<a.length;k++) {
if(a[j] == a[k]) {
count++;
}
}
if(count==1){
System.out.println(a[j]);
}
count = 0;
}
}
/*
for array of non duplicate elements in array just change int k=j+1; to int k = 0; in for loop
*/
static void NonDuplicateItem(int[] a){
/*
You can sort the array before you compare
*/
int temp =0;
for(int i=0; i<a.length;i++){
for(int j=0; j<a.length;j++){
if(a[i]<a[j]){
temp = a[i];
a[i] = a[j];
a[j] = temp;
}
}
}
int count=0;
for(int j=0;j<a.length;j++) {
for(int k =0 ;k<a.length;k++) {
if(a[j] == a[k]) {
count++;
}
}
if(count==1){
System.out.println(a[j]);
}
count = 0;
}
}
public class DuplicateItem {
public static void main (String []args){
int[] a = {1,1,1,2,2,3,6,5,3,6,7,8};
duplicateItem(a);
NonDuplicateItem(a);
}
/// for first non repeating element in array ///
static void FirstNonDuplicateItem(int[] a){
/*
You can sort the array before you compare
*/
int temp =0;
for(int i=0; i<a.length;i++){
for(int j=0; j<a.length;j++){
if(a[i]<a[j]){
temp = a[i];
a[i] = a[j];
a[j] = temp;
}
}
}
int count=0;
for(int j=0;j<a.length;j++) {
//int k;
for(int k =0; k<a.length;k++) {
if(a[j] == a[k]) {
count++;
}
}
if(count==1){
System.out.println(a[j]);
break;
}
count = 0;
}
}
public class NonDuplicateItem {
public static void main (String []args){
int[] a = {1,1,1,2,2,3,6,5,3,6,7,8};
FirstNonDuplicateItem(a);
}
I have a unique answer, it basically takes the current number that you have in the outer for loop for the array and times it by itself (basically the number to the power of 2). Then it goes through and every time it sees the number isn't equal to double itself test if its at the end of the array for the inner for loop, it is then a unique number, where as if it ever find a number equal to itself it then skips to the end of the inner for loop since we already know after one the number is not unique.
public class Solution {
public int singleNumber(int[] arr){
int size = arr.length;
int temp = 0;
int result = 0;
int temp2 = 0;
int temp3 = 0;
boolean flag = true;
int[] arr1 = new int[size];
for(int i=0;i<size;i++){
temp = arr[i];
temp2 = temp*temp;
for(int j=0;j<size;j++){
temp3 = temp*arr[j];
if(temp2==temp3 && i!=j)
j=arr.length
if(temp2 != temp3 && j==arr.length){
//System.out.println("Match found for "+temp);
flag = false;
result = temp;
break;
}
}
}
return result;
}
public static void main(String[] args) {
int[] a = {1,1,3,2,3};
Solution sol = new Solution();
System.out.println("SINGLE NUMBER : "+sol.singleNumber(a));
}
}
not tested but should work
public class Solution {
public int singleNumber(int[] arr){
int size = arr.length;
int temp = 0;
int result = 0;
boolean flag = true;
int[] arr1 = new int[size];
for(int i=0;i<size;i++){
temp = arr[i];
int count=0;
for(int j=0;j<size;j++){
if(temp == arr[j]){
count++;
}
}
if (count==1){
result=temp;
break;
}
}
return result;
}
Try:
public class Answer{
public static void main(String[] args) {
int[] a = {1,1,3,2,3};
int[] b =new int[a.length];
//instead of a.length initialize it to maximum element value in a; to avoid
//ArrayIndexOutOfBoundsException
for(int i=0;i<a.length;i++){
int x=a[i];
b[x]++;
}
for(int i=0;i<b.length;i++){
if(b[i]==1){
System.out.println(i); // outputs 2
break;
}
}
}
}
PS: I'm really new to java i usually code in C.
Thanks #dasblinkenlight...followed your method
public class Solution {
public int singleNumber(int[] arr){
int size = arr.length;
int temp = 0;
int result = 0;
int[] arr1 = new int[size];
for(int i=0;i<size;i++){
boolean flag = true;
temp = arr[i];
for(int j=0;j<size;j++){
if(temp == arr[j]){
if(i != j){
// System.out.println("Match found for "+temp);
flag = false;
break;
}
}
}
if(flag == true)
result = temp;
}
return result;
}
public static void main(String[] args) {
int[] a = {1,1,3,2,3};
Solution sol = new Solution();
System.out.println("SINGLE NUMBER : "+sol.singleNumber(a));
}
}
One disastrous mistake was not enclosing the content of if(i != j) inside braces. Thanks all for your answers.
If you are coding for learning then you can solve it with still more efficiently.
Sort the given array using merge sort of Quick Sort.
Running time will be nlogn.
The idea is to use Binary Search.
Till required element found All elements have first occurrence at even index (0, 2, ..) and next occurrence at odd index (1, 3, …).
After the required element have first occurrence at odd index and next occurrence at even index.
Using above observation you can solve :
a) Find the middle index, say ‘mid’.
b) If ‘mid’ is even, then compare arr[mid] and arr[mid + 1]. If both are same, then the required element after ‘mid’ else before mid.
c) If ‘mid’ is odd, then compare arr[mid] and arr[mid – 1]. If both are same, then the required element after ‘mid’ else before mid.
Another simple way to do so..
public static void main(String[] art) {
int a[] = { 11, 2, 3, 1,1, 6, 2, 5, 8, 3, 2, 11, 8, 4, 6 ,5};
Arrays.sort(a);
System.out.println(Arrays.toString(a));
for (int j = 0; j < a.length; j++) {
if(j==0) {
if(a[j]!=a[j+1]) {
System.out.println("The unique number is :"+a[j]);
}
}else
if(j==a.length-1) {
if(a[j]!=a[j-1]) {
System.out.println("The unique number is :"+a[j]);
}
}else
if(a[j]!=a[j+1] && a[j]!=a[j-1]) {
System.out.println("The unique number is :"+a[j]);
}
}
}
Happy Coding..
Using multiple loops the time complexity is O(n^2), So the effective way to resolve this using HashMap which in the time complexity of O(n). Please find my answer below,
`public static int nonRepeatedNumber(int[] A) {
Map<Integer, Integer> countMap = new HashMap<>();
int result = -1;
for (int i : A) {
if (!countMap.containsKey(i)) {
countMap.put(i, 1);
} else {
countMap.put(i, countMap.get(i) + 1);
}
}
Optional<Entry<Integer, Integer>> optionalEntry = countMap.entrySet().stream()
.filter(e -> e.getValue() == 1).findFirst();
return optionalEntry.isPresent() ? optionalEntry.get().getKey() : -1;
}
}`

Shifting and Re-organizing Arrays

I have an array, let's say: LRU_frame[] = {4,1,0,3}
I have a random() function that spits out a random number. If the random number n is contained in the array LRU_frame, then, n should be on LRU_frame[0] and everything else must be shifted down accordingly.
For example if random() gives me a 0, the new LRU_frame[] = {0,4,1,3}
Another example, if random() gives me a 3, the new LRU_frame[] = {3,4,1,0}
How do I do this for any Array size with any number of elements in it?
I know how to shift arrays by adding a new element on LRU_frame[0] but have no idea on how to re-organize the array like I need.
This is the code I have so far and let's assume char a is the random number(casted into char) to use and re-organize the array.
public static void LRU_shiftPageRef(char a) {
for (int i = (LRU_frame.length - 2); i >= 0; i--) {
LRU_frame[i + 1] = LRU_frame[i];
}
LRU_frame[0] = a;
}
You have a good idea, you only need to find the position of the a element in the array and start the cycle from it, instead of LRU_frame.length.
int index = -1;
// find the positon of 'a' in the array
for (int i = 0; i <= (LRU_frame.length - 1); i++) {
if (LRU_frame[i] == a) {
index = i;
break;
}
}
// if it is present, do roughly the same thing as before
if (index > -1) {
for (int i = (index - 1); i >= 0; i--) {
LRU_frame[i + 1] = LRU_frame[i];
}
LRU_frame[0] = a;
}
However if you can use ArrayLists it gets much easier.
// declaration
ArrayList<Integer> LRU_frame = new ArrayList<Integer>();
...
if (LRU_frame.contains(a)) {
LRU_frame.remove((Integer) a);
LRU_frame.add(0, a);
}
I think this could be the sort of thing you are after:
public static void LRU_shiftPageRef(char a) {
int index = indexOf(a);
if (index == -1) {
//not currently in array so create a new array 1 bigger than existing with a in newArray[0] or ignore depending on functionality required.
} else if (index > 0) {
//Set first entry as a and shift existing entries right
char insertChar = a;
char nextChar = LRU_frame[0];
for (int i =0; i < index; i++) {
LRU_frame[i] = insertChar;
insertChar = nextChar;
nextChar = LRU_frame[i+1];
}
LRU_frame[index] = insertChar;
} else {
//do nothing a is already at first position
}
}
public static int indexOf(char a) {
for (int i=0; i < LRU_frame.length; i++) {
if (LRU_frame[i] == a) {
return i;
}
}
return -1;
}
Use Arrays.sort(LRU_frame); to sort the entire array, or Arrays.sort(LRU_frame, fromIndex, toIndex)); to sort part of the array.
Arrays class has other useful methods like copyOfRange.

bubbleSort() for an int Array Linked List in Java

I'm having trouble with a bubbleSort method for my very unique homework assignment.
We are supposed to use a sorting method of our choice to sort, get this, a linked list of int arrays. Not an ArrayList not just a LinkedList. It works like a linked list but the each Node contains an array of a capacity of 10 ints.
I am stuck on the sorting method. I chose bubbleSort just because it was used in the last assignment and I felt most familiar with it. Any tips for a better sorting method to try would be considered helpful as well.
Here is my code:
public void bubbleSort() {
current = head; // Start at the head ArrayNode
for (int i = 0; i < size; i++) { // iterate through each ArrayNode
currentArray = current.getArray(); // get the array in this ArrayNode
int in, out;
for (out = size-1; out > 1; out--) { // outer loop (backwards)
for (in = 0; in < out; in++) { // inner loop (forwards)
if (currentArray[in] > currentArray[in+1]) // out of order?
swap(in, in+1); // swap them!
}
}
current.setArray(currentArray);
current = current.getNext();
}
}// End bubbleSort() method
// A helper method for the bubble sort
private void swap(int one, int two) {
int temp = currentArray[one];
currentArray[one] = currentArray[two];
currentArray[two] = temp;
} // End swap() method
This is a picture example of what I am supposed to be doing.
I have found a solution with selectionsort. There are a few test values, just run it to see it.
I can provide further information if needed.
import java.util.ArrayList;
import java.util.Random;
public class ArrayedListSort {
int listsize = 5; // how many nodes
int maxValue = 99; // the highest value (0 to this)
int nodeSize = 3; // size for every node
public static void main(String[] args) {
// run non static
new ArrayedListSort().runTest();
}
/**
* Log function.
*/
public void log(Object s) {
System.out.println(s);
}
public void logNoBR(Object s) {
System.out.print(s);
}
/**
* Output of list we have.
*/
public void logMyList(ArrayList<ListNode> listNode, String name) {
log("=== LOG OUTPUT " + name + " ===");
for ( int i=0; i < listNode.size(); i++) {
logNoBR(" node <" + i + ">");
logNoBR(" (");
for (int j=0; j < listNode.get(i).getSize(); j++) {
if ( j != (listNode.get(i).getSize()-1)) // if not last add ","
logNoBR( listNode.get(i).getValueAt(j) + "," );
else
logNoBR( listNode.get(i).getValueAt(j) );
}
log(")");
}
log("=====================================\n");
}
public void runTest() {
// create example List
ArrayList<ListNode> myList = new ArrayList<ListNode>();
// fill the nodes with random values
for ( int i = 0; i < listsize; i++) {
myList.add(new ListNode(nodeSize));
for (int j=0; j < nodeSize; j++) {
int randomValue = new Random().nextInt(maxValue);
myList.get(i).addValue(randomValue);
}
}
logMyList(myList, "myList unsorted"); // to see what we have
// now lets sort it
myList = sortListNode(myList);
logMyList(myList, "myList sorted"); // what we have after sorting
}
/**
* Selectionsort
*/
public ArrayList<ListNode> sortListNode(ArrayList<ListNode> myList) {
ArrayList<ListNode> retList = new ArrayList<ListNode>();
for ( int i = 0; i < listsize; i++) {
retList.add(new ListNode(nodeSize));
}
int lastSmallest = myList.get(0).getValueAt(0);
while ( !myList.isEmpty() ) {
int lastJ=0, lastI=0;
for ( int i = 0; i < myList.size(); i++) {
for (int j=0; j < myList.get(i).getSize(); j++) {
if ( myList.get(i).getValueAt(j) <= lastSmallest ) {
lastSmallest = myList.get(i).getValueAt(j);
lastJ = j;
lastI = i;
//log("Found smallest element at <"+i+","+j+"> (" + lastSmallest + ")");
}
}
}
myList.get(lastI).removeValue(lastJ);
if ( myList.get(lastI).getSize() == 0 )
myList.remove(lastI);
// add value to new list
for ( int i = 0; i < listsize; i++) {
if ( retList.get(i).getSize() < retList.get(i).getMaxSize() ) {
retList.get(i).addValue(lastSmallest);
break;
}
}
lastSmallest = Integer.MAX_VALUE;
}
return retList;
}
public class ListNode {
private ArrayList<Integer> values = new ArrayList<Integer>();
private int maxSize;
public ListNode(int maxSize) {
this.maxSize = maxSize;
}
public ArrayList<Integer> getValues() {
return values;
}
public int getMaxSize() {
return maxSize;
}
public int getSize() {
return values.size();
}
public int getValueAt(int position) {
if ( position < values.size())
return values.get(position);
else
throw new IndexOutOfBoundsException();
}
public void addValue(int value) {
values.add(value);
}
public void removeValue(int position) {
if ( position < values.size()) {
values.remove(position);
} else
throw new IndexOutOfBoundsException();
}
}
}
Here we go. The trivial solution consist in extracting all the elements of each array node and store them in a single big array, sort that big array (using Bubble Sort, Quick Sort, Shell Sort, etc.) and finally reconstruct the linked list of arrays with the the sorted values. I am almost sure that is not exactly what are you looking for.
If you want to sort the numbers in place, I can think of the following algorithm:
As others have commented, you need a comparison function that determines if a node A goes before a node B. The following algorithm use the first idea but for each pair of nodes, e.g. A->[3, 9, 7] and B->[1, 6, 8] becomes [1, 3, 6, 7, 8, 9] and finally A->[1,3, 6] and B->[7, 8, 9]. If we apply this rearrangement for each possible pair will end up with a sorted linked list of arrays (I have no proof, though).
A = head;
while (A.hasNext()) {
arrayA = A.getArray();
B = A.getNext();
while (B.hasNext()) {
arrayB = B.getArray();
// concatenate two arrays
int[] C = new int[arrayA.size() + arrayB.size()];
int i;
for (i = 0; i < arrayA.size(); i++)
C[i] = arrayA[i];
for ( ; i < arrayA.size() + arrayB.size(); i++)
C[i] = arrayB[i-arrayA.size()];
// sort the new arrays using agains Bubble sort or any
// other method, or Arrays.sort()
Arrays.sort(C);
// now return the sorted values to the two arrays
for (i = 0; i < arrayA.size(); i++)
arrayA[i] = C[i];
for (i = 0; i < arrayB.size(); i++)
arrayB[i] = C[i+arrayA.size()];
}
}
This is kind of pseudo code because I haven't worked with linked lists in Java but I think you get the idea.
NOTE: I haven't tested the code, it may contain horrors.

Find majority element in an array in java

I am trying to find out the majority Element in an array ad this code is working fine when I am checking with elements less than size. But it is giving me arrayindexoutofbound exception whenever any element is equal to size of array. Please let me know how to resolve this.
public class MajorityElement {
public static void main(String[] args) {
int a[]={2,2,7,5,2,2,6};
printMajority(a, 7);
}
//1st condition to check if element is in majority.
public static int findCandidate(int a[], int size){
int maj_index=0;
int count =1;
int i;
size=a.length;
for(i=1;i<a.length;i++ ){
if(a[maj_index]==a[i])
count++;
else
count--;
if(count==0)
{
maj_index=a[i]; //current element takes max_inex position.
count =1;
}
}
return a[maj_index];
}
public static boolean isMajority(int a[], int size, int cand){
int i, count =0;
for(i=0;i<a.length;i++)
{
if(a[i]==cand)
count++;
}
if(count>size/2){
return true;
}
else {
return false;
}
}
private static void printMajority(int a[],int size){
size=a.length;
int cand=findCandidate( a, 7);
if(isMajority(a,size,cand))
System.out.printf("%d",cand);
else
System.out.println("no such element as majority");
}
}
The problem is in the maj_index=a[i]; line. You take the value of one of the cells of the array and assign it to maj_index which is subsequently used as an index into the array (see a[maj_index] == a[i]). Thus, if the value at that position was larger than the size of the array an out-of-bounds situation will occur.
Here's your code slightly revised. In particular, I got rid of the maj_index variable so that the index vs. value mixup cannot happen. I also used a for-each loop for (int current : a) instead of the for-loop for(int i = 0; i < a.length; ++i). Finally, I eliminated the the size parameter (no need to pass it, it can be inferred from the array itself via a.length)
public class MajorityElement {
// 1st condition to check if element is in majority.
public static int findCandidate(int a[]) {
int cand = a[0];
int count = 1;
for (int i = 1; i < a.length; i++) {
if (cand == a[i])
count++;
else
count--;
if (count == 0) {
cand = a[i];
count = 1;
}
}
return cand;
}
public static boolean isMajority(int a[], int cand) {
int count = 0;
for (int current : a) {
if (current == cand)
count++;
}
return count > a.length / 2;
}
private static void printMajority(int a[]) {
int cand = findCandidate(a);
if (isMajority(a, cand))
System.out.printf("%d", cand);
else
System.out.println("no such element as majority");
}
public static void main(String[] args) {
int a[] = { 9, 7, 9, 5, 5, 5, 9, 7, 9, 9, 9, 9, 7 };
printMajority(a);
}
}
Problem is with your :
for(i=1;i<a.length;i++ ){
if(a[maj_index]==a[i])
count++;
else
count--;
if(count==0)
{
maj_index=a[i]; //current element takes max_inex position.
count =1;
}
}
return a[maj_index];
here you are getting the value as like :a[maj_index] for a test data int a[]={2,1,8,8,8,8,6}; the elemnt 8 is the major but a[maj_index] is invalid which is causing the issue,
Instead Complete code can be like below:
public class TestMajor {
/**
* #param args
*/
public static void main(String[] args) {
int a[]={2,1,8,8,8,8,6};
printMajority(a, 7);
}
//1st condition to check if element is in majority.
public static int findCandidate(int a[], int size){
int test = a[0];
int count =1;
int i;
size=a.length;
for(i=1;i<a.length;i++ ){
if(test ==a[i])
count++;
else
count--;
if(count==0)
{
test =a[i]; //current element takes max_inex position.
count =1;
}
}
return test;
}
public static boolean isMajority(int a[], int size, int cand){
int i, count =0;
for(i=0;i<a.length;i++)
{
if(a[i]==cand)
count++;
}
if(count>size/2){
return true;
}
else {
return false;
}
}
private static void printMajority(int a[],int size){
size=a.length;
int cand=findCandidate( a, 7);
if(isMajority(a,size,cand))
System.out.printf("%d",cand);
else
System.out.println("no such element as majority");
}
}
Majority Element in an Array using Java 8 OR Find the element appeared max number of times in an array :
public class MajorityElement {
public static void main(String[] args) {
int[] a = {1,3,4,3,4,3,2,3,3,3,3,3};
List<Integer> list = Arrays.stream(a).boxed().collect(Collectors.toList());
Map<Integer, Long> map = list.parallelStream()
.collect(Collectors.groupingBy(Function.identity(),Collectors.counting()));
System.out.println("Map => " + map);
//{1=1, 2=1, 3=8, 4=2}
map.entrySet()
.stream()
.max(Comparator.comparing(Entry::getValue))//compare the values and get the maximum value
.map(Entry::getKey)// get the key appearing maximum number of times
.ifPresentOrElse(System.out::println,() -> new RuntimeException("no such thing"));
/*
* OUTPUT : Map => {1=1, 2=1, 3=8, 4=2}
* 3
*/
System.out.println("...............");
// A very simple method
//method 2
Integer maxAppearedElement = list.parallelStream().max(Comparator.comparing(Integer::valueOf)).get();
System.out.println(maxAppearedElement);
}//main
}

Categories

Resources