虽然直接排序冒泡排序二分查找数组反转都有数组类的方法可以实现,但是面试或者平时经常需要用到。记录一下。
package cn.itcast.others; import java.util.Arrays; //直接排序(选择排序) public class SortDemo1 { public static void main(String[] args) { int[] arr = { 7, 3, 6, 8, 5, 4 }; System.out.println(Arrays.toString(arr)); //每次用1个元素与所有元素比较 for (int i = 0; i < arr.length - 1; i++) { for (int j = i + 1; j < arr.length; j++) { if (arr[i] > arr[j]) { int temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; } } System.out.println(Arrays.toString(arr)); } } }
package cn.itcast.others; import java.util.Arrays; //冒泡排序 public class SortDemo2 { public static void main(String[] args) { int[] arr = { 7, 3, 6, 8, 5, 4 }; System.out.println(Arrays.toString(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; System.out.println(Arrays.toString(arr)); } } } } }
package cn.itcast.others; import java.util.Arrays; //二分查找(需要先对数组排序) public class HalfSearchDemo1 { public static void main(String[] args) { int[] arr = { 7, 3, 6, 8, 5, 4 }; Arrays.sort(arr); System.out.println(Arrays.toString(arr)); System.out.println(halfSearch(arr, 5)); } public static int halfSearch(int[] arr, int key) { int min = 0; int max = arr.length - 1; int mid = (min + max) / 2; while (arr[mid] != key) { if (key > arr[mid]) { min = mid + 1; } else if (key < arr[mid]) { max = mid - 1; } if (min > max) { return -1; } } return mid; } }
package cn.itcast.others; //数组反转 import java.util.Arrays; public class ReverseArrDemo1 { public static void main(String[] args) { int[] arr = { 7, 3, 6, 8, 5, 4 }; System.out.println(Arrays.toString(arr)); for (int start = 0, end = arr.length - 1; start < end; start++, end--) { int temp = arr[start]; arr[start] = arr[end]; arr[end] = temp; } System.out.println(Arrays.toString(arr)); } }