如何使用 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[] a = { 2, 5, -2, 6, -3, 8, 0, -7, -9, 4 };
      int target = 0;
      
      for (int i = 0; i < a.length; i++) {
         if (a[i] == target) {
            System.out.println("Element found at index " + i);
            break;
         } 
      } 
   }
}

結果

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

Element found at index 6 

氣泡排序

以下的示例演示使用氣泡排序排序陣列元素。

public class HelloWorld {
   static void bubbleSort(int[] arr) {
      int n = arr.length;
      int temp = 0;
      for(int i = 0; i < n; i++) {
         for(int j=1; j < (n-i); j++) {
            if(arr[j-1] > arr[j]) { 
               temp = arr[j-1]; 
               arr[j-1] = arr[j];
               arr[j] = temp;
            } 
         } 
      } 
   }  
   public static void main(String[] args) {
      int arr[] = { 2, 5, -2, 6, -3, 8, 0, -7, -9, 4 }; 
      System.out.println("Array Before Bubble Sort");
      
      for(int i = 0; i < arr.length; i++) {
         System.out.print(arr[i] + " ");
      } 
      System.out.println();
      bubbleSort(arr);
      System.out.println("Array After Bubble Sort");
      
      for(int i = 0; i < arr.length; i++) {
         System.out.print(arr[i] + " ");
      } 
   }  
}  

結果

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

Array Before Bubble Sort
2 5 -2 6 -3 8 0 -7 -9 4 
Array After Bubble Sort
-9 -7 -3 -2 0 2 4 5 6 8      
java_arrays.htm
廣告
© . All rights reserved.