数组中常见的算法
例如:java中提供了一个数组工具类:java.util.Arrays
Arrays是一个工具类。
其中有一个sort()方法,可以排序。静态方法,直接使用类名调用就行。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
| import java.util.Arrays;
public class ArraysTest02 { public static void main(String[] args) { int[] arr = {3,6,4,5,12,1,2,32,5,5}; Arrays.sort(arr); for (int i = 0; i < arr.length; i++) { System.out.println(arr[i]); } int index = Arrays.binarySearch(arr, 5);
System.out.println(index == -1 ? "该元素不存在" : "该元素下标是:" + index); } }
|
排序
冒泡排序
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74
|
public class BubbleSort { public static void main(String[] args) {
int[] arr = {9, 8, 10, 7, 6, 0, 11};
int count2 = 0; for(int i = arr.length-1; i > 0; i--){ for(int j = 0; j < i; j++){ if(arr[j] > arr[j+1]){ int temp; temp = arr[j]; arr[j] = arr[j+1]; arr[j+1] = temp; count2++; } } }
System.out.println("交换位置的次数:" + count2); for (int i = 0; i < arr.length; i++) { System.out.println(arr[i]); } } }
|
选择排序
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83
|
public class SelectSort { public static void main(String[] args) {
int[] arr = {9, 8, 10, 7, 6, 0, 11};
int count = 0; int count2 = 0;
for(int i = 0; i < arr.length - 1; i++){ int min = i; for(int j = i+1; j < arr.length; j++){ count++; if(arr[j] < arr[min]){ min = j; } }
if(min != i){ int temp; temp = arr[min]; arr[min] = arr[i]; arr[i] = temp; count2++; } }
System.out.println("比较次数" + count); System.out.println("交换次数:" + count2);
for (int i = 0; i < arr.length; i++) { System.out.println(arr[i]); } } }
|
查找——二分查找(binarySearch)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72
| package com.bjpowernode.javase.array;
public class ArrayUtil { public static void main(String[] args) {
int[] arr = {100,200,230,235,600,1000,2000,9999};
int index = binarySearch(arr, 230); System.out.println(index == -1 ? "该元素不存在!" : "该元素下标" + index); }
public static int binarySearch(int[] arr, int dest) { int begin = 0; int end = arr.length - 1; while(begin <= end) { int mid = (begin + end) / 2; if (arr[mid] == dest) { return mid; } else if (arr[mid] < dest) { begin = mid + 1; } else { end = mid - 1; } } return -1; } }
|