why is this not executing in vs code editor? - java

public class binsearch {
public static void main(String args[])
{
int arr[]={2,45,-21,56,23};
int target=45;
int answer=binarysearch(arr, target);
System.out.println(answer);
}
static int binarysearch(int arr[],int target)
{
int start=0;
int end=arr.length-1;
int mid=start+end/2;
while(start<=end)
{
if(target<arr[mid])
{
mid=end-1;
}
else if(target>arr[mid])
{
mid=mid+1;
}
else
{
return mid;
}
}
return -1;
}
}
I have tried running this code multiple times but it just doesnt run. I dont think there is any problem with the logic for binary search in this code. Please do help.Thank you.

Your code runs. It has an infinite loop so it never terminates.
In order for a binary search to work. The array must be sorted in ascending order. So just sort the array before you do the binary search. Below code uses class java.util.Arrays to sort the array but you can sort it anyway you like. Just make sure that the array is sorted before you do the binary search.
Also, the calculation of mid needs to be inside the while loop because it always changes since its value is determined by the values of both start and end and those values are changed inside the while loop.
Note that I changed the name of the class so as to adhere to Java naming conventions. The conventions make it easier for other people to read and understand your code.
import java.util.Arrays;
public class BinSearch {
static int binarysearch(int arr[], int target) {
int start = 0;
int end = arr.length - 1;
while (start <= end) {
int mid = start + ((end - start) / 2);
if (target < arr[mid]) {
end = mid - 1;
}
else if (target > arr[mid]) {
start = mid + 1;
}
else {
return mid;
}
}
return -1;
}
public static void main(String[] args) {
int arr[] = {2, 45, -21, 56, 23};
Arrays.sort(arr);
int target = 45;
int answer = binarysearch(arr, target);
System.out.println(answer);
}
}
The answer is 3 because, after the sort, 45 is the second last element in the [sorted] array because it is the second largest number in the array.
If you want to search without sorting the array then a binary search is not appropriate.

Related

How to recursively count number of occurences in an array

I've got a task that gets an int value "n" and an Int Array as parameters and is supposed to return a boolean.
The method is supposed to determine, how many "n" are in the given Array. If the number is even the method should return true, else false. If the Array has the length 0, it should return "false" aswell.
What i managed to do is :
public static boolean evenNumberOf(int n, int[] arr) {
boolean result = false;
System.out.println("Starting count");
if (n < arr.length) {
if (arr[n] == n) {
result = true;
} else {
return evenNumberOf(n - 1, arr);
}
}
return result;
}
Im just really confused and i dont know what to do to be honest. I have really tried my best but the longer i work on this task the less i understand.
Any help is appreciated and thank you in advance! :)
Separate it into two methods:
The method you call initially
and a method that gets called recursively to count the number of ns in the array:
boolean evenNumberOf(int n, int[] arr) {
int count = countNs(n, arr, 0);
// Logic to choose what to return based on count and/or length of arr.
}
int countNs(int n, int[] arr, int i) {
// Check if arr[i] is equal to n.
// Make a recursive call to countNs for i := i + 1.
// Combine the check/recursive call result to return a value.
}
Try
//arr should not be empty, index and count >= 0
public static boolean evenNumberOf(int value, int index,int[]arr, int count) {
if(index >= arr.length) return count%2 == 0;
if(arr[index] == value ) {
count++;
}
return evenNumberOf(value, ++index, arr, count);
}
Usage example: System.out.println(evenNumberOf(2, 0, new int[]{2,0,3,7,6,11,1,2}, 0));
(You can add an helper method evenNumberOf(int value,int[]arr))
as Recursive Counting in an Array got closed as a duplicate I will answer it here:
Let's analyze what you did and why it's wrong
public static int countN(int n,int [] arr,int i, int count) {
if (arr[i] == n) {
System.out.println("MATCH");
count++;
return count;
}
Here you already return the count when you get a match. You shouldn't do that because if the first number is already the same it returns 1. all you need to do is increase the count here
else {
System.out.println("Moving on");
i = i + 1;
countN(n,arr,i, count);
}
Here you do the recursion. This is good. But this also needs to be done in the case that you do get a match. And it needs to return that value. But, also this only needs to be done when you are not at the end of the array yet
if (arr.length == i) {
evenNumberOf(n,arr);
}
this part doesn't make sense, because you call evenNumberOf with the exact same arguments as it started so it will result in an infinite loop. you should have returned the count here. also keep in mind that the last index of an array is length - 1
putting this together you can make:
public static int countN(int n,int [] arr,int i, int count) {
if (arr[i] == n) {
count++;
}
if (arr.length - 1 == i) {
return count;
}
return countN(n, arr, i + 1, count);
}

Binary search does not work with doubles

This program works very well with integers, but not doubles. There are no errors, but the program returns -1. Sorry if this is a stupid question, but I am new to programming.
public class binarySearchProject
{
public static int binarySearch(double[] arr, double x, int high, int low)
{
int mid=(high+low)/2;
if(high==low || low==mid || high==mid)
{
return -1;
}
if(arr[mid]>x)
{
return binarySearch(arr, x, high, mid);
}
else if(arr[mid]<x)
{
return binarySearch(arr, x, mid, low);
}
else if(arr[mid]==x)
{
return mid;
}
return -1;
}
public static void main(String args[])
{
double i = 45.3;
double[] a = {-3, 10, 5, 24, 45.3, 10.5};
int size = a.length;
System.out.println(binarySearch(a, i, size, 0));
}
}
You should change the conditions:
if (arr[mid] > x) should be if (arr[mid] < x)
else if (arr[mid] < x) should be else if (arr[mid] > x)
Also note that in order to make this work, the array must be sorted (That's the whole point of binary search), you can use Arrays#sort:
Arrays.sort(a);
I recommend you rename your class so it begins with an upper case (Following Java Naming Conventions).
As #tobias_k pointed out:
For binary search to work, you need to sort the array first.
See Wikipedia for details.

binary search on a array with a string prefix

How can i go about adding the elements of a sorted array which contain a specific string prefix using binary search and those elements as the order they appear in the array to a arraylist..
It is not hard to code but i am having difficulty with binary search. To use the string prefix the String class provides startswith. I just need help to start the binary search
public static <T extends Comparable<T>> ArrayList prefixMatch(T[] list,
String prefix) {
}
Use the binarySearch method from the API.
String[] objString = {"a","b","c"};
System.out.println(Arrays.binarySearch(objString,"c"));
Or if you want to create your own Binary search implementation. Here it is.
/* BinarySearch.java */
public class BinarySearch {
public static final int NOT_FOUND = -1;
public static int search(int[] arr, int searchValue) {
int left = 0;
int right = arr.length - 1;
return binarySearch(arr, searchValue, left, right);
}
private static int binarySearch(int[] arr, int searchValue, int left, int right) {
if (right < left) {
return NOT_FOUND;
}
/*
int mid = mid = (left + right) / 2;
There is a bug in the above line;
Joshua Bloch suggests the following replacement:
*/
int mid = (left + right) >>> 1;
if (searchValue > arr[mid]) {
return binarySearch(arr, searchValue, mid + 1, right);
} else if (searchValue < arr[mid]) {
return binarySearch(arr, searchValue, left, mid - 1);
} else {
return mid;
}
}
}
public class BinarySearchTest {
public static void main(String[] args) {
int[] arr = {1, 5, 2, 7, 9, 5};
Arrays.sort(arr);
System.out.println(BinarySearch.search(arr, 2));
}
}
I had a similar requirement - given the array of Strings find indexes of each string which starts with a new letter, i.e. for Africa Angela Beach Bamboo Zorro, I needed algorithm which would return [ 0, 2, 4 ]
I found that there's a modification of well known Binary Search algorithm which uses 'deferred equality test' and this has the side effect of finding exactly needed indexes - ones which start the range.
You can read about it in this Wikipedia article (also there's a very simple example based on which I implemented my own).

Select i th smallest element from an array

I have a divide and conquer method to find the i th smallest element from an array. Here is the code:
public class rand_select{
public static int Rand_partition(int a[], int p, int q, int i) {
//smallest in a[p..q]
if ( p==q) return a[p];
int r=partition (a,p,q);
int k=r-p+1;
if (i==k) return a[r];
if (i<k){
return Rand_partition(a,p,r-1,i);
}
return Rand_partition(a,r-1,q,i-k);
}
public static void main(String[] args) {
int a[]=new int []{6,10,13,15,8,3,2,12};
System.out.println(Rand_partition(a,0,a.length-1,7));
}
public static int partition(int a[],int p,int q) {
int m=a[0];
while (p < q) {
while (p < q && a[p++] < m) {
p++;
}
while (q > p && a[q--] > m) {
q--;
}
int t = a[p];
a[p] = a[q];
a[q] = t;
}
int k=0;
for (int i=0; i < a.length; i++) {
if ( a[i]==m){
k=i;
}
}
return k;
}
}
However, I get an exception when run: java.lang.ArrayIndexOutOfBoundsException.
I was able to fix a few bugs. A minor one is this line:
return Rand_partition(a,r-1,q,i-k);
^
Instead, you want this:
return Rand_partition(a,r+1,q,i-k);
^
That's because you have partitioned a[p..q] into three parts as follows:
a[p..r-1], a[r], a[r+1..q]
Your original code handles the a[r] and a[p..r-1] case fine, but messes up on the a[r+1..q] by using r-1 instead.
I was also able to correct and simplify partition:
public static int partition(int a[],int p,int q){
int m=a[p]; // not m[0], you want to partition m[p..q]!!!
while ( p<q){
while (p<q && a[p] <m){ // don't do p++ here!
p++;
}
while (q>p && a[q]>m){ // don't do q-- here!
q--;
}
int t=a[p];
a[p]=a[q];
a[q]=t;
}
return p; // no need to search!!!
}
Your original code had extraneous p++ and q--. Also, the search for where the pivot is is unnecessary. It's where p and q meet.
On naming conventions
Please follow Java naming conventions:
Class names should be nouns, in mixed case with the first letter of each internal word capitalized. Methods should be verbs, in mixed case with the first letter lowercase, with the first letter of each internal word capitalized.
Related questions
How is this statement making sense? (Sun’s naming convention for Java variables)
Unfortunately the naming convention document above has one glaring error
On array declarations
Also, do not make a habit of declaring arrays like this:
int x[];
You should instead put the brackets with the type, rather than with the identifier:
int[] x;
Related questions
Is there any difference between Object[] x and Object x[] ?
Difference between int[] myArray and int myArray[] in Java
in array declaration int[] k,i and int k[],i
These declarations result in different types for i!
Assuming this isn't homework where you need do it this way, and it's not in the critical path (which is a likely guess), just sort the array and grab the value at index i.
public static getIthSmallest(final int[] myArray, final int i) {
if (i < 0) {
System.err.println("You're going to get an ArrayIndexOutOfBoundsException.");
}
if (i >= myArray.length) {
System.err.println("You're going to get an ArrayIndexOutOfBoundsException.");
}
Arrays.sort(myArray);
return myArray[i];
}
No clue what your bug is (I dislike Java :)
The simple solution (O(n) average, O(n^2) worst case) to this problem is copy the source to a nice simple implementation of qsort and make it only recurse on the side that contains the position you care about. It should be about 5 lines of code different so it should be easy to do.
If i is small there is a O(n + log(n)*i*log(i)) solution):
int FindI(int[] array, int i)
{
int[] tmp = array[0..i].dup; // copy first i elements;
sort(tmp); // sort, low to high
foreach(j in array[i..$]) // loop over the rest
if(j < tmp[0])
{
tmp[0] = j;
sort(tmp);
}
return tmp[0];
}
The algorithm you're attempting to implement is called Quickselect. Here is a link to working code using a median-of-three partitioning strategy.
You can use public static T min(Collection coll, Comparator comp) in Collections.

Quicksort algorithm program in Java

I'm trying to implement QuickSort algorithm program in Java, but I'm getting incorrect answer.
public class QuickSort {
public static void main(String[] args){
int arr[]={12,34,22,64,34,33,23,64,33};
int i=0;
int j=arr.length;
while(i<j){
i=quickSort(arr,i,i+1,j-1);
}
for(i=0;i<arr.length;i++)
System.out.print(arr[i]+" ");
}
public static int quickSort(int arr[],int pivot,int i,int j){
if(i>j) {
swap(arr,pivot,j);
return i;
}
while(i<arr.length&&arr[i]<=arr[pivot]) {
i++;
}
while(j>=1&&arr[j]>=arr[pivot]) {
j--;
}
if(i<j)
swap(arr,i,j);
return quickSort(arr,pivot,i,j);
}
public static void swap(int[] arr,int i,int j) {
int temp;
temp=arr[i];
arr[i]=arr[j];
arr[j]=temp;
}
}
The above program giving me the output as: 12 23 22 33 34 33 64 34 64
Could anyone please tell me how can I get my desire result?
The problem is that this is not really how quicksort works. Quicksort is a recursive algorithm that should only be called once from outside of itself. The idea is that at each iteration, you partition the array into two halves - the left half contains all elements less than the pivot, and the right half contains all elements greater than / equal to the pivot. Then you quicksort the two halves, and finally put the pivot in the middle.
If the side that you are quicksorting is less than 3 elements long, you can just swap the two elements or leave them, and that part of the array is done.
But it doesn't look like your code is doing that at all - you are calling Quicksort 6 times from your client, and within the quicksort function you are making at most one swap. So this is not a case where someone is going to be able to look at your code and debug it by telling you to move a swap or something. You need to revisit your logic.
Check out the Wikipedia diagram for a visual example of what is supposed to happen in a single iteration:
http://en.wikipedia.org/wiki/File:Partition_example.svg
There are open source implementations of quicksort in Apache Harmony and Apache Mahout, probably amongst many others. You can read them.
public static int partition(int[] a, int p, int r){
int i=p,j=r,pivot=a[r];
while(i<j){
while(i<r && a[i] <= pivot){
i++;
}
while(j>p && a[j]>pivot){
j--;
}
if(i<j){
swap(a, i, j);
}
}
return j;
}
public static void quickSort(int[] a, int p, int r){
if(p<r){
int q=partition(a, p, r);
if(p==q){
quickSort(a, p+1, r);
}else if(q==r){
quickSort(a, p, r-1);
}else {
quickSort(a, p, q);
quickSort(a, q+1, r);
}
}
}
public static void swap(int[] a, int p1, int p2){
int temp=a[p1];
a[p1]=a[p2];
a[p2]=temp;
}
here is a quicksort algorithm
package drawFramePackage;
import java.awt.geom.AffineTransform;
import java.util.ArrayList;
import java.util.ListIterator;
import java.util.Random;
public class QuicksortAlgorithm {
ArrayList<AffineTransform> affs;
ListIterator<AffineTransform> li;
Integer count, count2;
/**
* #param args
*/
public static void main(String[] args) {
new QuicksortAlgorithm();
}
public QuicksortAlgorithm(){
count = new Integer(0);
count2 = new Integer(1);
affs = new ArrayList<AffineTransform>();
for (int i = 0; i <= 128; i++){
affs.add(new AffineTransform(1, 0, 0, 1, new Random().nextInt(1024), 0));
}
affs = arrangeNumbers(affs);
printNumbers();
}
public ArrayList<AffineTransform> arrangeNumbers(ArrayList<AffineTransform> list){
while (list.size() > 1 && count != list.size() - 1){
if (list.get(count2).getTranslateX() > list.get(count).getTranslateX()){
list.add(count, list.get(count2));
list.remove(count2 + 1);
}
if (count2 == list.size() - 1){
count++;
count2 = count + 1;
}
else{
count2++;
}
}
return list;
}
public void printNumbers(){
li = affs.listIterator();
while (li.hasNext()){
System.out.println(li.next());
}
}
}
also available with description at nathan's computer knowledge with a description
[code]
[/code]
``
Your loop is not working properly. Refer the code which is solve your problem about Quick Sort
static void quickSort (int[] numbers, int low, int high)
{
int i=low;
int j=high;
int temp;
int middle=numbers[(low+high)/2];
while (i<j) {
while (numbers[i]<middle) {
i++;
}
while (numbers[j]>middle) {
j--;
}
if (i<=j) {
temp=numbers[i];
numbers[i]=numbers[j];
numbers[j]=temp;
i++;
j--;
}
}
if (low<j) {
quickSort(numbers, low, j);
}
if (i<high) {
quickSort(numbers, i, high);
}
}
Refer Quick sort.
Please find comprehensive working code for quick sort algorithm implemented in Java here,
http://tech.bragboy.com/2010/01/quick-sort-in-java.html

Categories