Commit 264a7935 authored by Margarita's avatar Margarita Committed by GitHub

Last realize

just made nicer code)
parent f9b0dbdf
import java.util.Arrays;
public class test {
public static int binarySearch(int ar[], int first, int last, int X){
int mid = (first + last)/2;
while( first <= last ){
if ( (ar[mid] < X) & ((ar[mid-1]) >= X)){
return mid;
}
else if (ar[mid] < X){
last = mid - 1;
}
else {
first = mid + 1;
}
mid = (first + last)/2;
}
return -1;
}
public static void main(String[] args) {
//create random array
System.out.print("\nRandom Array: \n");
int ar[] = new int[20];
for (int i = 0; i < ar.length; i++) {
ar[i] = (int)(Math.random()*100);
System.out.print(ar[i] + " ");
}
//My trick for simple sort
System.out.print("\nNegative array: \n");
for (int i = 0; i < ar.length; i++) {
ar[i] = ar[i]*(-1);
System.out.print(ar[i] + " ");
}
//Sort array and return positive numbers)
System.out.print("\nSorted Array: \n");
Arrays.sort(ar);
for(int i = 0; i < ar.length; i++) {
ar[i] = ar[i]*(-1);
System.out.print(ar[i] + " ");
}
//I just choose this number)
int X = 17;
System.out.print("\nX = " + X);
//call my binary search
int last = ar.length-1;
int first = 0;
int index = binarySearch(ar,first,last,X);
if (index != -1) {
System.out.println("\n" + X + " more than first_index_number: " + index);
} else {
System.out.println("\nsomething wrong");
}
}
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment