冒泡排序
private void maopao(int arr[]) {
for (int i = 0; i < arr.length; i++) {
for (int j = 0; j < arr.length - 1; j++) {
if (arr[j] > arr[j + 1]) {
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
}
选择排序
private void xuanze(int[] arr) {
for (int i = 0; i < arr.length; i++) {
int min = arr[i];
int x = -1;
boolean b = false;
for (int j = i; j < arr.length; j++) {
if (arr[j] < min) {
b = true;
min = arr[j];
x = j;
}
}
if (b) {
int temp = arr[i];
arr[i] = min;
arr[x] = temp;
}
}
}
插入排序
1 private void charu(int[] arr2) {
2 int[] arr = new int[arr2.length];
3 for (int i = 0; i < arr2.length; i++) {
4 arr[i] = arr2[i];
5 for (int j = 0; j < i; j++) {
6 if (arr[i] >= arr[j] && arr[i] <= arr[j + 1]) {
7 arr = houyi(arr, j, i);
8 }
9 }
10 }
11 }
12
13 /**
14 * 指定位置后移
15 *
16 * @param arr
17 * @param j
18 * @param i
19 * @return
20 */
21 private int[] houyi(int[] arr, int j, int i) {
22 int temp = arr[i];
23 for (int k = i; k > j; k--) {
24 arr[k] = arr[k - 1];
25 }
26 arr[j] = temp;
27 return arr;
28 }
希尔排序
1 /**
2 * 希尔排序
3 *
4 * @param arr
5 */
6 private void xier(int[] arr) {
7 for (int i = arr.length / 2; i > 0; i = i / 2) {
8 for (int j = i; j < arr.length; j++) {
9 for (int k = j - i; k >= 0; k -= i) {
10 if (arr[k] > arr[i + k]) {
11 int temp = arr[k];
12 arr[k] = arr[k + i];
13 arr[k + i] = temp;
14 }
15 }
16 }
17 }
18 }
快速排序
1 /**
2 * 快速排序
3 *
4 * @param arr
5 * @param left
6 * @param right
7 */
8 private void kuaisu(int[] arr, int left, int right) {
9 int l = left;
10 int r = right;
11 int pivot = arr[(left + right) / 2];
12 int temp = 0;
13 while (l < r) {
14 while (arr[l] < pivot) {//寻找左边第一个不小于pivot的索引
15 l += 1;
16 }
17 while (arr[r] > pivot) {//寻找右边第一个不大于pivot的索引
18 r -= 1;
19 }
20 if (l >= r) {
21 break;
22 }
23 temp = arr[l];
24 arr[l] = arr[r];
25 arr[r] = temp;//左右位置的值互换
26 if (arr[l] == pivot) {
27 r -= 1;
28 }
29 if (arr[r] == pivot) {
30 l += 1;
31 }
32 }
33 if (l == r) {
34 l += 1;
35 r -= 1;
36 }
37 if (left < r) {
38 kuaisu(arr, left, r);
39 }
40 if (right > l) {
41 kuaisu(arr, l, right);
42 }
43 }
基数排序(桶排序)
1 private static void radix(int[] arr) {
2 int max=arr[0];
3 for (int i = 1; i <arr.length ; i++) {
4 if (arr[i]>max){
5 max=arr[i];
6 }
7 }
8 int maxleng=(max+"").length();
9 for (int i = 0,n=1; i <maxleng ;n*=10, i++) {
10 int[][] arr2=new int[10][arr.length];
11 int[] indexs=new int[10];
12 int index=0;
13 for (int j = 0; j <arr.length ; j++) {
14 int yushu=arr[j]/n%10;
15 arr2[yushu][indexs[yushu]]=arr[j];
16 indexs[yushu]++;
17 }
18 for (int j = 0; j <arr2.length ; j++) {
19 for (int a = 0; a <indexs[j] ; a++) {
20 arr[index++]=arr2[j][a];
21 }
22 }
23 }
24 }