Binary search and bubblesort problem. Cant understand the problem with binary search pseudocode.What do i need to change in order to get the index of targeted number?
import java.util.*;
public class Binarysearch2 {
static void bubblesort(int dizi[]){ // bubblesort //
int o,p,temp;
for(o=0;o<dizi.length-1;o++)
{
for(p=0;p<dizi.length-1-o;p++)
{
if(dizi[p+1]>dizi[p]){
temp=dizi[p];
dizi[p]=dizi[p+1];
dizi[p+1]=temp;
}
}
}
}
static int search(int dizi[],int aranan) // binary search//
{
int ust=dizi.length-1;
int alt=0;
while(alt<=ust)
{
int orta=(alt+ust)/2;
if(dizi[orta]==aranan){
return orta;
}
else if (orta<aranan)
{
alt=orta+1;
}
else
ust=orta-1;
}
return -1;
}
public static void main(String[]args) //main//
{
Scanner tara=new Scanner(System.in);
System.out.println("Enter array lenght");
int x=tara.nextInt();
Random rnd= new Random();
int i;
int a[]=new int[x];
for(i=0;i<x;i++)
{
a[i]=(1+rnd.nextInt(6));
System.out.print(a[i]+" ");
}
System.out.println();
System.out.println("Enter targeted number :");
int k,z;
k=tara.nextInt();
bubblesort(a);
z=Binarysearch2.search(a,k);
if(z==-1)
{System.out.println("Target is not in array.");}
else
System.out.println(k+" in array "+z +" . at this index.");
}}
i think something in binarysearch is wrong.
Good day, It would be really helpful if you'll be using english to name variables. Binary search making an important assumption, that array, where you are seeking for an element, has been sorted. So, if you would add sorting into search method as such, your code will work: