Why is my code not working though I've tried dry running it 1000 times, but still I'm not able to find my doubt, maybe I'm short of the knowledge which will help me find the mistake, can anybody help me with this?
package _08_Arrays;
public class _04_Binary_Search {
public static void main(String[] args) {
int arr[] = { 5, 3, 2, 4, 1 };
int target = 2;
SortArray(arr);
System.out.print(BinarySearch(arr, target));
}
public static int BinarySearch(int[] arr, int target) {
int s = 0; // I took int s=arr[0] which will provide inconvenience in case if I want do s++
// or s--, it will increase the value of the element in the array by one.
int n = arr.length;
int e = n - 1;
for(;s<=e;) {
int mid=(s+e)/2;
if(arr[mid]>target) {
e=mid-1;
} else if(arr[mid]<target) {
s=mid+1;
} else {
return mid;
}
}
return -1;
}
public static void SortArray(int[] arr) {
// TODO Auto-generated method stub
int idx=-1;
int sort=0;
for(int j=0;j<arr.length;j++) {
int min=Integer.MAX_VALUE;
for(int i=sort;i<arr.length;i++) {
if(arr[i]<min) {
min=arr[i];
idx=i;
}
}
int temp=arr[sort];
arr[sort]=min;
arr[idx]=temp;
sort++;
}
}
}
I tried to get the index of the element which I tend to pass in the target element, but I'm getting different index of the element in the array which is different from the actual index of elements of the array.
dsais about something else. Removed tag.