氣泡排序,選擇排序、二分法查詢圖示以及程式碼實現
阿新 • • 發佈:2018-11-03
氣泡排序
請看下面的這個栗子:
需要排序的陣列arr = {99,88,77,55,66,44};
具體排序細節各位客官請看圖:
程式碼實現:
public class BubbleSort { public static void main(String[] args) { int[] arr = {99,88,77,55,66,44}; bubbleSort(arr); System.out.println(Arrays.toString(arr)); } public static void bubbleSort(int[] arr){ for (int i=0;i<arr.length;i++){ for(int j=0;j<arr.length-i-1;j++){ if(arr[j]>arr[j+1]){ int temp = arr[j]; arr[j]=arr[j+1]; arr[j+1]=temp; } } } } }
選擇排序
請看下面第二個栗子:
需要排序的陣列arr = {99,88,77,55,66,44};
public class selectSort { public static void main(String[] args) { int[] arr = {99, 88, 77, 55, 66, 44}; selectSort(arr); System.out.println(Arrays.toString(arr)); } public static void selectSort(int[] arr) { int index; for (int i = 0; i < arr.length; i++) { index = i; for(int j=i;j<arr.length;j++){ if(arr[index]>arr[j]){ int temp = arr[index]; arr[index] = arr[j]; arr[j] = temp; } } } } }
二分法查詢
二分法查詢的前提是陣列必須是按照升序排列的。比如下面這個栗子
arr = {44,55,66,77,88,99};
請看程式碼實現
public class BinarySearch { public static void main(String[] args) { int[] arr = {44, 55, 66, 77, 88, 99}; int i = binarySearch(arr, 55); System.out.println(i); } public static int binarySearch(int[] arr, int ele) { int minIndex = 0; int maxIndex = arr.length - 1; int midIndex = (minIndex + maxIndex) / 2; while (minIndex <= maxIndex) { if (ele == arr[midIndex]) { return midIndex; } else if (ele > arr[midIndex]) { minIndex = midIndex + 1; } else if (ele < arr[midIndex]) { maxIndex = midIndex - 1; } midIndex = (minIndex + maxIndex) / 2; } return -1; } }