1.请实现以下函数int indexOf(int[] array, int target), 给定一个循环有序的数组。请在这个数组中找到指定元素,找到的话返回小标,没有找到返回-1.该数组的特点是它是一个单调递增的数组向右循环移位形成的。举例说明,原数组是[4,8,13,20,23,34,41,52]经过右循环移位后形成的数组可能是[23,34,41,52,4,8,13,20],也可能是[4,8,13,20,23,34,41,52]
实现代码一:(遍历)
import java.util.Scanner; public class LoopArray { public static void main(String[] args){ int[] array = {4,8,13,20,23,34,41,52}; Scanner in = new Scanner(System.in); int num = in.nextInt(); System.out.print("the number " + num + " is in array ?"); System.out.println(" "); if(loopArrayFind(array, num) == -1){ System.out.println("NO!"); }else if((loopArrayFind(array, num) >= 0)&&(loopArrayFind(array, num) < array.length)){ System.out.println("YES!"); }else{ System.out.println("Error!"); } } public static int loopArrayFind(int[] array, int num){ int flag = 0; for(int i = 0; i < array.length; i++){ if(array[i] == num){ flag = i; break; }else flag = -1; } return flag; } }
实现代码二:(遍历+不使用break)
import java.util.Scanner; public class LoopArray { public static void main(String[] args){ int[] array = {4,8,13,20,23,34,41,52}; Scanner in = new Scanner(System.in); int num = in.nextInt(); System.out.print("the number " + num + " is in array ?"); System.out.println(" "); if(loopArrayFind(array, num) == -1){ System.out.println("NO!"); }else if((loopArrayFind(array, num) >= 0)&&(loopArrayFind(array, num) < array.length)){ System.out.println("YES!"); }else{ System.out.println("Error!"); } } public static int loopArrayFind(int[] array, int num){ int flag = -1; for(int i = 0; i < array.length; i++){ if(array[i] == num){ flag = i; }else; } return flag; } }
实现代码三:(QuickSort)
import java.util.Scanner; public class LoopArray { public static void main(String[] args){ int[] array = {23,34,41,52,4,8,13,20}; Scanner in = new Scanner(System.in); int num = in.nextInt(); System.out.print("the number " + num + " is in array ?"); System.out.print(" "); if(loopArrayFind(array, num) == -1){ System.out.println("NO!"); }else if((loopArrayFind(array, num) >= 0)&&(loopArrayFind(array, num) < array.length)){ System.out.println("YES!"); }else{ System.out.println("Error!"); } } public static int loopArrayFind(int[] array, int num){ int flag = -1; int low = 0; int high = array.length; int middle = (low+high)/2; while(middle > 0){ if(num == array[middle]){ flag = middle; }else if(num < array[middle]){ if(num <= array[middle-1]){ if(num == array[middle-1]){ flag = middle-1; }else{ high = middle - 1; } }else; }else{ if(middle < array.length){ if(num == array[middle+1]){ flag = middle+1; }else{ low = middle+1; } }else; } middle = (low + high)/2; } return flag; } }