Bug in beginner Binary search - java

It shows the output when the Search value(SV) is present in the array. But not if it is not there. It keeps asking for input and keeps looping.
This is my first time attempting to make a code for binary search
import java.util.Scanner;
public class Binary_search {
public static void main() {
Scanner input = new Scanner(System.in);
int start = 0;
int end = arr.length;
//I used flag to end the loop
int Flag = 0;
int mid = 0;
int SV = input.nextInt();
//here I enter values in the array
for (int x = 0; x <= 4; x++) {
arr[x] = input.nextInt();
}
//here I start a loop for the search
while (Flag == 0) {
mid = (start + end) / 2;
if (mid == SV) {
System.out.println("Number Found" + arr[mid]);
Flag = Flag + 1;
} else if (mid > SV) {
end = mid - 1;
} else if (mid < SV) {
start = mid + 1;
}
//this was the second possibility if the number was not present
else if (start == end) {
Flag = Flag + 1;
System.out.println("Number not found");
}
}
}
}
If the SV is present in the array it will show what position it is in, "Number Found" + arr[mid]. But if it is not there it is supposed to output, "Number not found", however, this does not happen and it keeps asking for input.

You can create simple way like this.
Please compare and check where you need to correct.
public class Test {
public static void main(String[] args) {
int arr[] = { 10, 20, 30, 40, 50 };
int key = 3;
binarySearchExample(arr, key);
}
public static void binarySearchExample(int arr[], int key) {
int first = 0;
int last = arr.length - 1;
int mid = (first + last) / 2;
while (first <= last) {
if (arr[mid] < key) {
first = mid + 1;
} else if (arr[mid] == key) {
System.out.println("Element is found at index: " + mid);
break;
} else {
last = mid - 1;
}
mid = (first + last) / 2;
}
if (first > last) {
System.out.println("Element is not found!");
}
}
}

You can create a class like this to input the numbers from the user and store it in an array and search another inputted number in the array with binary search and display its location.
import java.util.*;
class BinarySearch
{
public static void main()
{
int i, num, item, array[], first, last, middle;
Scanner sc = new Scanner(System.in);
System.out.println("Enter number of elements:");
num = sc.nextInt();
//array gets created by inputted space
array = new int[num];
System.out.println("Enter " + num + " integers");
for (i = 0; i < num; i++)
array[i] = sc.nextInt();
System.out.println("Enter the number to be searched:");
item = sc.nextInt();
first = 0;
last = num - 1;
middle = (first + last)/2;
//search starts
while( first <= last )
{
if ( array[middle] < item )
first = middle + 1;
else if ( array[middle] == item )
{
//number found in
System.out.println(item + " is found at location " + (middle + 1));
break;
}
else
{
last = middle - 1;
}
middle = (first + last)/2;
}
if ( first > last )
//number not found in array
System.out.println(item + " is not found.\n");
}
}

Related

How to check if all elements of a arrayList is the same?

I am making a program that is going to print out based on who is the winner. (More details about
the task in the link) https://open.kattis.com/problems/vote
I have trouble with printing out "no winner" at the right value. I am tryng to print out "no winner" only when all elements in my arrayList is the same. ex.
arr = [10, 10, 10]
then print out:
"no winner"
How do i check if all elements in a arrayList is equal?
import java.util.ArrayList;
import java.util.Collections;
import java.util.Scanner;
public class B {
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
int testCase = sc.nextInt();
for (int i = 0; i < testCase; i++ ) {
int candidate = sc.nextInt();
int maximum = 0;
int winner = 0;
boolean tie = false;
ArrayList<Integer> votes = new ArrayList<>();
for (int j = 0; j < candidate; j++) {
int nVotes = sc.nextInt();
votes.add(nVotes);
}
int imax = votes.indexOf(Collections.max(votes));
int max = Collections.max(votes); // max winner
int in = votes.indexOf(votes);
int index = imax + 1;
int sum = 0;
for(int o = 0; o < votes.size(); o++)
{
sum = sum + votes.get(o);
if (votes.get(o) == votes.get(o) ) {
tie = true;
}
}
if (max > (sum / 2)) {
System.out.println("majority winner " + index);
}
else if (max < (sum / 2)) {
System.out.println("minority winner " + index);
}
else if (votes.get(i) == votes.get(i)) {
System.out.println("no winner");
}
}
}
}
Try using what you've done to set the tie case to true, like:
else if (tie == true) {
System.out.println("no winner");
}

java unable to find the error to print a prime number

This program gets 4 input from the user and prints out all the pairs except for the duplicate pairs. I wanted it print only the pairs that sum equals a prime number. I did the entire program there is no compilation error but in the output it prints to all pairs except the duplicate pair(i want it to print only the pair whose sum= a prime number) can anyone tell me what i am doing wrong
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class Prime {
public static List<Integer> numbers = new ArrayList<>(); // a list of integers that was accepted, can be acced in the order they were added
public static Scanner input = new Scanner(System.in);
public static void main(String args[])
{
int inputs = 4;
input(inputs);
for(int i = 0; i < inputs; i++){
for(int j = 0+i; j < inputs; j++){
if(i != j)
System.out.println(numbers.get(i)+ " + " + numbers.get(j) + " = "+ isPrime(numbers.get(i) + numbers.get(j)));
}
} }
public static int isPrime (int sumPair)
{
boolean primeVal =true ;
if(sumPair < 2)
primeVal= false;
else if(sumPair ==2)
primeVal=true;
else if (sumPair % 2 == 0)
primeVal = false;
else
{
int stop = (int)Math.sqrt(sumPair);
for (int d = 3; d <= stop && primeVal; d = d + 2)
{
if (sumPair % d == 0)
primeVal = false;
}
}
return(sumPair);
}
public static void input(int inputNumbers)
{
while(numbers.size() < inputNumbers){ // while there is more inputs needed
System.out.print("Enter a positive integer: ");
int num = input.nextInt();
if(num > 0) // if the input is valid
numbers.add(num);
else // if the input is not valid
while (num <= 0) { // while the input is not valid
System.out.print("Enter a positive integer: ");
num = input.nextInt(); // get the next int if it wasn't valid
if(num > 0) { // if the input gets valid
numbers.add(num);
}
}
System.out.println("Thank you.");
}
}
public static int sumPair(int num1, int num2)
{
return num1 + num2;
}
}
You go to a lot of trouble to compute a boolean primeVal which tells whether the input be true or false, but you never actually return this value. Try this instead:
public static boolean isPrime (int sumPair) {
boolean primeVal = true;
if (sumPair < 2 || sumPair % 2 == 0) {
primeVal = false;
}
else {
int stop = (int)Math.sqrt(sumPair);
for (int d=3; d <= stop; d += 2) {
if (sumPair % d == 0) {
primeVal = false;
break;
}
}
}
return primeVal;
}
Use this main() method:
public static void main (String args[]) {
int inputs = 4;
input(inputs);
for (int i=0; i < inputs-1; i++) {
for (int j=i+1; j < inputs; j++) {
boolean prime = isPrime(numbers.get(i) + numbers.get(j));
if (prime) {
System.out.println(numbers.get(i) + " + " + numbers.get(j));
}
}
}
}
Your condition to determine if you print the current pair or not is if(i != j), so it will only print if i is different from j (duplicate).
You made a nice isPrime function, you should call it.
You made your isPrime function return an int, and I'm pretty sure it should return a boolean instead. Also, it returns the argument you gave it, so it does virtually nothing except spend time in a potentially expensive operation. Perhaps should it return primeVal instead.
Your code should look like:
for(int i = 0; i < inputs; i++){
for(int j = 0+i; j < inputs; j++){
ni = numbers.get(i);
nj = numbers.get(j);
if(isPrime(ni+nj)){
System.out.println(ni + " + " + nj + " = "+ (ni + nj));
}
}
}
What this does is get the numbers for indexes i and j and store them in ni and nj respectively. Then, it checks it their sum is prime. If it is, then it prints the sum.

java - Input 2 integer arrays and print alternating elements

Conditions:
both arrays must be in order or error message
the first array must be as long as or longer than the second or error message
if the first is longer than the second it must continue to print the first
Example: given setF[] = 1,2,3,4,8 and setS[] =5,6,7 it prints 1, 5, 2, 6, 3, 7, 4, 8
The Problem With My Code: It will print and alternate fine, but will not continue to print the first areay if it's longer.
full code (I apologize for slightly messy formatting. The website screwed it up a little bit):
package mergearrays;
import java.io.*;
import java.lang.*;
import java.util.*;
public class MergeArrays {
public static void main(String[] args) {
//variables
boolean done = false;
boolean error = false;
int inpval = 0;
int i = 0; //will be setF.length
int j = 0; //will be setS.length
//arrays
int [] vals = new int[20000];
//ask user
System.out.println("Enter the values for the first array, up to 10000 values, enter zero or a negative number to quit");
//input array
Scanner scan = new Scanner(System.in);
while(!done) {
inpval = scan.nextInt();
if (inpval > 0) {
vals[i] = inpval;
i++;
}
else {
done = true;
}
}
done = false;
System.out.println("Enter the values for the second array, up to 10000 values, enter zero or a negative number to quit");
while(!done) {
inpval = scan.nextInt();
if (inpval > 0) {
vals[j+i+1] = inpval;
j++;
}
else {
done = true;
}
}
//new arrays
int [] setF = new int[10000];
int [] setS = new int[10000];
//copy vals into setF and setS
System.arraycopy(vals, 0, setF, 0, i);
System.arraycopy(vals, i+1, setS, 0, i+j+1);
//check for order
for (int p = 0; p < i - 1; p++) {
if (setF[p] > setF[p+1]) {
error = true;
break;
}
}
for (int b = 0; b < j - 1; b++) {
if (setS[b] > setS[b+1]) {
error = true;
break;
}
}
//print first array
System.out.print("\n First Array: ");
for(int q = 0; q < i; q++) {
System.out.print(setF[q] + " ");
}
//print second array
System.out.print("\n Second Array: ");
for(int m = 0; m < j; m++) {
System.out.print(setS[m] + " ");
}
//print the final set
if(i >= j && error == false){
System.out.print("\n Merged Array: ");
for(int n = 0; n <= i+j; n++) {
if(setF[n] != 0 && setS[n] !=0) {
if(n <= j) {
System.out.print(setF[n] + " ");
System.out.print(setS[n] + " ");
}
else if(n > j && n <= i){
System.out.print(setF[n] + " ");
}
}
}
}
//error message
else {
System.out.print("\n ERROR: Array not in correct order");
}
}
}
the reason it didn't continue to print for you if the first array is longer lies in this line of code:
if (setF[n] != 0 && setS[n] != 0) {
You continued to print only if both of the array at the same position were zero. You should check here 'OR' not 'AND'. In addition, after changing that condition to 'OR', the ifs inside need to be changed as well, because the indexes are not correct. As follows:
System.out.print("\n Merged Array: ");
for (int n = 0; n <= i + j; n++) {
if (setF[n] != 0 || setS[n] != 0) {
if (n < j) {
System.out.print(setF[n] + " ");
System.out.print(setS[n] + " ");
} else if (n < i) {
System.out.print(setF[n] + " ");
}
}
}
I would have solved it in a different way, and I can guide you to if you need some help. Anyways, Hope this helps...

Getting the second highest and second lowest java

Getting the second highest and second lowest java without using array array sort or any sorting method, min_value and max_value just for loop and if statement I already started to code this is what ive done so far i cant think of how can i get the second lowest and second highest
package Lab2;
import java.util.Scanner;
public class hehe {
public static void main(String[] args) {
int fh, sh, fl, sl, x;
Scanner s = new Scanner(System.in);
System.out.print("Enter 5 numbers: ");
x = fh = sh = sl = fl = s.nextInt();
int a,b,c,d;
int mid = 0;
for (int i = 0; i < 4; ++i) {
int n = s.nextInt();
if (fh < n) {
fh = n;
}
if (fl > n) {
fl = n;
}
for(int y=0;y<5;y++){
}
}
System.out.println("The First highest is: " + fh);
System.out.println("The Second highest is: " + sh);
System.out.println("The Second lowest is: " + sl);
System.out.println("The First lowest is: " + fl);
System.out.println(mid);
}
}
Just improve upon your condition to cover all cases,
// Initialize your variables like this,
fh = sh = Integer.MIN_VALUE;
fl = sl = Integer.MAX_VALUE;
// Change your for loop condition to below and get input only inside the loop. Not before it.
for (int i = 0; i < 5; ++i) {
if (fh < n) { // It means you have received the highest known number
sh = fh; // The existing highest becomes the second highest now
fh = n; // n should now be the (first) highest rightfully
} else if (sh < n) { // This means n was not the highest, but second highest
sh = n;
}
// Do the same for lowest also.
Obviously, sorting the array is the obvious solution so I assume this is some sort of test assignment. Anyway, I guess the easiest way is just to have variables for both highest and 2nd highest (and same for lowest). For example, to find the 2nd highest:
List<Integer> values = new ArrayList<>();
for(int i = 0; i < 20; i++) {
values.add((int) (Math.random() * 10));
}
int highest = Integer.MIN_VALUE;
int second = Integer.MIN_VALUE;
for(int n: values) {
if(n > highest) {
second = highest;
highest = n;
} else if(n > second) {
second = n;
}
}
System.out.println("2nd highest: " + second);
if (fh < n) {
sh = fh;
fh = n;
}else if (sh < n)
{
sh = n;
}
if (fl > n) {
s1=f1
fl = n;
}else if (s1 > n)
{
s1 = n;
}
You need to also update the value of variable accordingly:
public static void main(String[] args) {
int fh, sh, fl, sl, x;
Scanner s = new Scanner(System.in);
System.out.print("Enter 5 numbers: ");
x = fh = sh = sl = fl = s.nextInt();
int a,b,c,d;
int mid = 0;
for (int i = 0; i < 4; ++i) {
int n = s.nextInt();
if (fh < n) {
sh = fh; // We have got new fh so sh is old value of fh.
fh = n;
}
if (fl > n) {
sl = fl;
fl = n;
}
}
System.out.println("The First highest is: " + fh);
System.out.println("The Second highest is: " + sh);
System.out.println("The Second lowest is: " + sl);
System.out.println("The First lowest is: " + fl);
}

The values output are all correct except for the Count on the first index

import java.util.*;
public class Test {
public static void main(String[] args)
{
int[] number = new int[50];
int index = 0;
boolean swap = true;
int temp;
Scanner keyboard = new Scanner(System.in);
System.out.print("Enter Number: ");
System.out.println(" ");
do
{
int input = keyboard.nextInt();
if (input != -999)
number[index++] = input;
else
break;
} while (index != 0);
int[] newNumbers = new int[index];
for (int i = 0; i < index; i++)
newNumbers[i] = number[i];
System.out.println("\nNumbers\t" + "Occurances");
goBack: for (int i = index - 1; i >= 0; i--)
{
for (int n = index - 1; n > i; n--)
if (newNumbers[n] == newNumbers[i])
continue goBack;
int count = 0;
for (int n = 0; n < index; n++)
if (newNumbers[n] == newNumbers[i])
count++;
for(int s=0; s < newNumbers.length-1; s++){
for(int j=1; j < newNumbers.length-s; j++){
if(newNumbers[j-1] > newNumbers[j]){
temp=newNumbers[j-1];
newNumbers[j-1] = newNumbers[j];
newNumbers[j] = temp;
}
}
}
System.out.println( newNumbers[i] + " " + count);
}
}
}
The code is intended to take the input through the keyboard scanner. The entered integers are compared and a list of distinct elements of the array number[] will be sorted and printed. However, The list of input contains multiples of some elements. The elements that are repeated are marked in a count. The final output should be a list of the distinct array elements (no duplicates) in order from greatest to least with their respective counts.
The input is as follows: -12, 3, -12, 4, 1, 1, -12, 1, -1, 1, 2, 3, 4, 2, 3, -12
when the sort is through and this prints, the index 4 has a count of four when it should have a count of 2. I have tried selection, bubble, and exchange sort algorithms all with similar results. Any advice would be greatly appreciated :) .
Hope this helps , though can be a better solution than this :
public static void main(String[] args) {
int[] numbers = new int[50] ;
int index = 0;
int temp;
Scanner keyboard = new Scanner(System.in);
// get the user input
System.out.print("Enter Number: ");
System.out.println(" ");
do {
int input = keyboard.nextInt();
if (input != -999)
numbers[index++] = input;
else
break;
} while (index != 0);
keyboard.close();
System.out.println("\nNumbers\t" + "Occurances");
// create a new array and store the user input
int[] newNumbers = new int[index];
for (int i = 0; i < index; i++)
newNumbers[i] = numbers[i];
// sort the array
for (int s = 0; s < newNumbers.length - 1; s++) {
for (int j = 1; j < newNumbers.length - s; j++) {
if (newNumbers[j - 1] < newNumbers[j]) {
temp = newNumbers[j - 1];
newNumbers[j - 1] = newNumbers[j];
newNumbers[j] = temp;
}
}
}
System.out.println(Arrays.toString(newNumbers));
int count = 1;
int prevElement = 0;
if (newNumbers.length > 0) {
prevElement = newNumbers[0];
}
// print the results
for (int x = 1; x < newNumbers.length; x++) {
if (newNumbers[x] == prevElement) {
count++;
} else {
System.out.println(prevElement + " occurs " + count + "times");
prevElement = newNumbers[x];
count = 1;
}
}
System.out.println(prevElement + " occurs " + count + "times");
}
Hi If you really want shorter one ::
import java.util.*;
public class Test {
public static void main(String[] args)
{
Integer number[] = new Integer[50];
int index = 0;
Scanner keyboard = new Scanner(System.in);
System.out.print("Enter Number: ");
System.out.println(" ");
do
{
int input = keyboard.nextInt();
if (input != -999)
number[index++] = input;
else
break;
} while (index != 0);
List<Integer> asList = Arrays.asList(number);
for(Integer n: asList){
if(n != null)
System.out.println(n + " occurance " + Collections.frequency(asList,n));
}
}
}

Categories

Resources