如何使用 Java 對陣列進行排序並在其中搜索元素



問題描述

如何對一個數組進行排序並從中搜索一個元素?

解決方案

以下示例展示如何使用 sort() 和 binarySearch() 方法來完成此任務。使用者定義的方法 printArray() 用於顯示輸出 −

import java.util.Arrays;

public class MainClass {
   public static void main(String args[]) throws Exception {
      int array[] = { 2, 5, -2, 6, -3, 8, 0, -7, -9, 4 };
      Arrays.sort(array);
      printArray("Sorted array", array);
      
      int index = Arrays.binarySearch(array, 2);
      System.out.println("Found 2 @ " + index);
   }
   private static void printArray(String message, int array[]) {
      System.out.println(message + ": [length: " + array.length + "]");
      for (int i = 0; i < array.length; i++) {
         if(i != 0){
            System.out.print(", ");
         }
         System.out.print(array[i]);
      } 
      System.out.println();
   }
}

結果

上述程式碼示例將生成以下結果。

Sorted array: [length: 10]
-9, -7, -3, -2, 0, 2, 4, 5, 6, 8
Found 2 @ 5

問題描述

如何比較兩個陣列?

public class HelloWorld { 
   public static void main (String[] args) {
      int arr1[] = {1, 2, 3};
      int arr2[] = {1, 2, 3};
      
      if (arr1 == arr2) System.out.println("Same"); 
      else System.out.println("Not same");
   } 
}

上述程式碼示例將生成以下結果。

Not same   

另一個數組比較示例

import java.util.Arrays;

public class HelloWorld { 
   public static void main (String[] args) { 
      int arr1[] = {1, 2, 3};
      int arr2[] = {1, 2, 3};
   
      if (Arrays.equals(arr1, arr2)) System.out.println("Same"); 
      else System.out.println("Not same");
   }
}

上述程式碼示例將生成以下結果。

Same   
java_arrays.htm
廣告
© . All rights reserved.