作业2 OO基础2-2、排序与查找
编码实现一个类,要求:
(1)提供一个静态方法,可以将输入的一个int[]数组按照从小到大的顺序排列;
(2)提供静态方法,对排好序的数组使用折半(二分)查找(使用递归和非递归两种形式分别实现)查找某一个整数。(30.0分)
代码
sort\Main.java
//sort\Main.java
package sort;
import sort.SortandFind;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int[] arr = new int[]{0, 9, 8, 7, 6, 5, 4, 3, 2, 1};
for (int j : arr) {
System.out.print(j + " ");
}
System.out.println();
System.out.println("Test sorting method:");
SortandFind.sort(arr);
for (int j : arr) {
System.out.print(j + " ");
}
System.out.println();
System.out.println("Test binary search method:");
System.out.println("Please enter the number you need to find x:");
int x = scanner.nextInt();
System.out.println("Recursive method:");
int Rec_position = SortandFind.Rec_bsearch(arr, x, 0, arr.length);
if (Rec_position == -1) {
System.out.println("Recursive method did not find " + x);
} else {
System.out.println("The Recursive method finds that the position of " + x + " in the " + Rec_position + " position");
}
System.out.println("Non-recursive method:");
int Nonrec_position = SortandFind.Nonrec_bsearch(arr, x);
if (Nonrec_position == -1) {
System.out.println("Non-recursive method did not find " + x);
} else {
System.out.println("The Non-recursive method finds that the position of " + x + " in the " + Nonrec_position + " position");
}
}
}
sort\SortandFind.java
//sort\SortandFind.java
package sort;
import java.util.Arrays;
public class SortandFind {
public static void sort(int[] arr) {
Arrays.sort(arr);
}
public static int Rec_bsearch(int[] arr, int x, int left, int right) {
int middle = (left + right) / 2;
if (left >= right) {
return -1;
}
if (x == arr[middle]) {
return middle;
}
if (x > arr[middle]) {
return Rec_bsearch(arr, x, middle + 1, right);
} else if (x < arr[middle]) {
return Rec_bsearch(arr, x, left, middle - 1);
}
return -1;
}
public static int Nonrec_bsearch(int[] arr, int x) {
int left = 0;
int right = arr.length;
while (left < right) {
int middle = (left + right) / 2;
if (x == arr[middle]) {
return middle;
}
if (x > arr[middle]) {
left = middle + 1;
}
if (x < arr[middle]) {
right = middle - 1;
}
}
return -1;
}
}