package javaArray; import java.sql.Date; public class A2 { public static void main(String[] args) { int a[] = new int[5]; Date[] days = new Date[3]; System.out.println(a[3]); System.out.println(days[2]); int[] data = new int[] {3, 9, 2, 8, 7, 0, 4, 6, 5, 1}; showArray(data); bubbleSort(data); showArray(data); selectSort(data); showArray(data); insertSort(data); showArray(data); } /** * showArray * @param data */ public static void showArray(int[] data) { for (int i = 0; i < data.length; i++) { System.out.print(data[i] + " "); } System.out.println(); } /** * bubbleSort * @param a */ public static void bubbleSort(int[] a) { int len = a.length; for (int i = 0; i < len - 1; i++) { for (int j = 0; j < len - i - 1; j++) { if (a[j] > a[j + 1]) { a[j] ^= a[j + 1]; a[j + 1] ^= a[j]; a[j] ^= a[j + 1]; } } } } /** * selectSort * @param a */ public static void selectSort(int[] a) { int len = a.length; for (int i = 0; i < len - 1; i++) { int tmp = i; for (int j = i + 1; j < len; j++) { if (a[tmp] < a[j]) { tmp = j; } } if (tmp != i) { a[tmp] ^= a[i]; a[i] ^= a[tmp]; a[tmp] ^= a[i]; } } } /** * insertSort * @param a */ public static void insertSort(int[] a) { for (int i = 1; i < a.length; i++) { for (int j = i; j > 0; j--) { if (a[j] < a[j - 1]) { a[j] ^= a[j - 1]; a[j - 1] ^= a[j]; a[j] ^= a[j - 1]; } else { break; } } } } }
<pre name="code" class="java"> /** * * @param a * @param num * @return */ public static int binarySearch(int[] a, int num) { int start = 0; int end = a.length - 1; int mid = (start + end) / 2; if (a.length == 0) return -2; while(start <= end) { if (a[mid] > num) { end = mid - 1; mid = (start - end) / 2; } else if (a[mid] < num) { start = mid + 1; mid = (start + end) / 2; } else { return mid; } } return -1; }