94.3k views
12 votes
Pseudocode to java

Can you write this in Java program

Binary Search

Pseudocode to java Can you write this in Java program Binary Search-example-1

2 Answers

10 votes

Answer: class Main {

public static void main(String[] args) {

int[] values = {11,12,15,16,112,118,123,145};

int target = 15;

int min = 0;

int high = values.length-1;

boolean found = false;

int answer = 0;

int mid;

while(!found && min <= high) {

mid = (min + high) / 2;

if (values[mid] == target) {

found = true;

answer = mid;

} else if (target > values[mid]) {

min = mid + 1;

} else {

high = mid - 1;

}

}

if (found) {

System.out.printf("%d FOUND AT ARRAY INDEX %d", target, answer);

} else {

System.out.printf("%d was not found", target);

}

}

}

Step-by-step explanation:

I altered the while expression to make the code work.

User Ken Prince
by
5.0k points
4 votes

Answer:

class Main {

public static void main(String[] args) {

int[] values = {11,12,15,16,112,118,123,145};

int target = 15;

int min = 0;

int high = values.length-1;

boolean found = false;

int answer = 0;

int mid;

while(!found && min <= high) {

mid = (min + high) / 2;

if (values[mid] == target) {

found = true;

answer = mid;

} else if (target > values[mid]) {

min = mid + 1;

} else {

high = mid - 1;

}

}

if (found) {

System.out.printf("%d FOUND AT ARRAY INDEX %d", target, answer);

} else {

System.out.printf("%d was not found", target);

}

}

}

Step-by-step explanation:

I altered the while expression to make the code work.

User Lxxyx
by
4.7k points