This is a Java Program to Find if a given Integer X appears more than N/2 times in a Sorted Array of N Integers.
Enter size of array and then enter all the elements of that array. Now enter the element you want to check. With the help of for loop now we check if it occurs mre than n/2 times or not.
Here is the source code of the Java Program to Find if a given Integer X appears more than N/2 times in a Sorted Array of N Integers. The Java program is successfully compiled and run on a Windows system. The program output is also shown below.
import java.util.Scanner;
public class Appear_Array
{
public static void main(String[] args)
{
int n, x, count = 0, i = 0, temp = 0;
Scanner s = new Scanner(System.in);
System.out.print("Enter no. of elements you want in array:");
n = s.nextInt();
int a[] = new int[n];
System.out.println("Enter all the elements:");
for(i = 0; i < n; i++)
{
a[i] = s.nextInt();
}
for(i = 0; i < n; i++)
{
for(int j = i + 1; j < n; j++)
{
if(a[i] > a[j])
{
temp = a[i];
a[i] = a[j];
a[j] = temp;
}
}
}
System.out.print("Enter the element which you want to check:");
x = s.nextInt();
for(i = 0; i < n; i++)
{
if(a[i] == x)
{
count++;
}
}
if(count > (n / 2))
{
System.out.println("Given Integer appears more than N/2 times");
}
else
{
System.out.println("Given Integer does not appear more than N/2 times");
}
}
}
Output:
$ javac Appear_Array.java $ java Appear_Array Enter no. of elements you want in array:5 Enter all the elements: 2 4 1 3 2 Enter the element which you want to check:2 Given Integer does not appear more than N/2 times
Sanfoundry Global Education & Learning Series – 1000 Java Programs.
advertisement
Here’s the list of Best Books in Java Programming, Data Structures and Algorithms.
Related Posts:
- Check Programming Books
- Apply for Computer Science Internship
- Practice Programming MCQs
- Check Java Books
- Practice Information Technology MCQs