Java Binary search not working -
i have insertion search in main , there call binarysearch method search number within array has been sorted. try compile errors here main insertion sort.
public class test5 { public static void main(string[] args) { // original order or numbers system.out.println("original order of numbers:"); int nums[] = {26, 45, 56, 12, 78, 74, 39, 22, 5, 90, 87, 32, 28, 11, 93, 62, 79, 53, 22, 51}; for(int x = 0; x < nums.length; x++){ system.out.print(nums[x] + " "); } // local variables int unsortedvalue; // first unsorted value int scan; // used scan array int swapcount = 0; // other loop steps index variable through // each subscript in array, starting @ 1. // because element 0 considered sorted. for(int index = 1; index < nums.length; index++) { // first element outside sorted subset // nums[index]. store value of elementt // in unsortedvalue. unsortedvalue = nums[index]; // start scan @ subscript of first element // proper position within sorted subset. scan = index; // move first element outside sorted subset // proper position within sorted subset. while(scan > 0 && nums[scan-1] > unsortedvalue) { nums[scan] = nums[scan -1]; scan--; } // insert unsorted value in proper position // within sorted subset. nums[scan] = unsortedvalue; swapcount++; } // print out results of swap , swapcount system.out.println(); system.out.println("insertion sort: "); for(int index = 0; index < nums.length; index++){ system.out.print(nums[index] + " "); } system.out.println(); system.out.println("the swap count is: " + swapcount); binarysearch(nums); } here method binary search
public static int binaryserach(string[] array, string value) { scanner keyboard = new scanner(system.in); system.out.print("enter target: "); int target = nums.nextint(); int index = -1; int left = 0; int right = nums.length - 1; int middle; while(left <= right){ middle = (left + right)/2; if(nums[middle] == target){ index = middle; break; } else if (nums[middle] > target) { right = middle - 1; }else{ left = middle + 1; } } if(index == -1){ system.out.println("element not found"); }else{ system.out.println("element found @ index " + index); } } }
errors cannot find symbol.
you have declared nums array locally inside main method, it's inaccessible anywhere else, e.g. binarysearch method. scope within main method.
declare static outside of methods can accessed method:
public class test5 { static int nums[] = {26, 45, 56, 12, 78, 74, 39, 22, 5, 90, 87, 32, 28, 11, 93, 62, 79, 53, 22, 51}; public static void main(string[] args) { ... additionally,
- you can't call
nextintonint[](nums). looks meant call onscannerobject:int target = keyboard.nextint(); - you aren't using of arguments
binarysearch- remove them. remove passingnumsin callbinarysearch. - it's typo here, declared method here
binaryserachinstead ofbinarysearch. - you aren't returning
binarysearchmethod, aren't assigning return of method either; make return typevoid.
Comments
Post a Comment