最新文章

LightBlog

2019/10/24

Java陣列搜尋及排序

import java.util.*;
public class UseArrays{
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int[] arr = {25, 17, 95, 47, 23, 3, 65 ,13, 50, 86, 77};
System.out.print(" 排序前: ");
for(int i = 0; i < arr.length; i++)
System.out.print(arr[i] + " ");

System.out.println();
Arrays.sort(arr);                                   // arr 陣列排序
System.out.print(" 排序後: ");
for(int i = 0; i < arr.length; i++)
System.out.print(arr[i] + " ");

int find;
System.out.print("\n 請輸入搜尋的值: ");
int key = scanner.nextInt();
if((find = Arrays.binarySearch(arr, key)) > -1) {
System.out.println(" 找到搜尋的值位於索引 " + find + " 位置");
}else
System.out.println(" 陣列中不存在搜尋的值");
}
}
----------------------------------------------- 輸出結果 --------------------------------------------
E:\test>java UseArrays
 排序前: 25 17 95 47 23 3 65 13 50 86 77
 排序後: 3 13 17 23 25 47 50 65 77 86 95
 請輸入搜尋的值: 3
 找到搜尋的值位於索引 0 位置

沒有留言:

Adbox