# Java陣列排序和搜尋

2019-10-16 22:30:51

``````package com.yiibai;

import java.util.Arrays;

public class ArraySortAndSearch {
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
``````

## 線性搜尋

``````package com.yiibai;

public class ArraySortAndSearch2 {
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
``````

## 氣泡排序

``````package com.yiibai;

public class ArraySortAndSearch3 {
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
``````