I am trying to write a binary search algorithm that searches and inserts into an array here is the code. What I did is the right moves 2 times the index and the left is 1. here is the code. I was also wondering if the search method is faster than a iterative loop that goes through the array one by one?
public class BinaryTree {
int root =0;
int right = 2;
int left = 1;
int arr[];
public void search(int arr[], int value){
if(arr[right] == value){
System.out.println("found");
return;
}
if(arr[left] == value){
System.out.println("found");
return;
}
else{
left+=1;
right+=2;
}
}
public void insert(int value, int arr[]) {
this.arr = arr;
if(arr[0]==0){
arr[0] = value;
root = arr[0];
System.out.println(root);
}
if(value>root){
if(arr[right]==0){
arr[right] = value;
right+=2;
}
}
if(value<root){
if(arr[left]==0){
arr[left] = value;
left+=1;
}else{
left+=1;
}
}
}
public void printint(){
for(int i=0;i<arr.length;i++){
System.out.print(arr[i]);
}
}
public static void main(String args[]) {
int tol[] = new int[9];
BinaryTree tree = new BinaryTree();
tree.insert(4, tol);
tree.insert(9,tol);
tree.insert(9, tol);
tree.insert(2, tol);
tree.search(tol, 9);
tree.printint();
}
}
is this considered a Binary search tree?