1、快排
import java.util.Arrays;
public class QuickRem {
public static void main(String[] args) {
int[] data = {9, -16, 21, 23, -30, -23, 22, 24, 22, 44, 45};
System.out.println("排序之前:" + Arrays.toString(data));
quickSort(data);
System.out.println("排序之后:" + Arrays.toString(data));
}
private static void quickSort(int[] data) {
if (data.length != 0) {
subSort(data, 0, data.length - 1);
}
}
private static void subSort(int[] data, int start, int end) {
if (start < end) {
int base = data[start];
int i = start;
int j = end + 1;
while (true) {
while (i < end && data[++i] <= base) ;
while (j > start && data[--j] >= base) ;
if (i < j)
swap(data, i, j);
else
break;
}
swap(data, start, j);
subSort(data, start, j - 1);
subSort(data, j + 1, end);
}
}
private static void swap(int[] data, int i, int j) {
int temp = data[i];
data[i] = data[j];
data[j] = temp;
}
}
2、归并排序
import java.util.Arrays;
public class MergeSort {
public static void main(String[] args) {
int[] data = {9, -16, 21, 23, -30, -23, 22, 24, 22, 44, 45};
System.out.println("排序之前:" + Arrays.toString(data));
mergeSort(data);
System.out.println("排序之后:" + Arrays.toString(data));
}
private static void mergeSort(int[] data) {
//归并排序
sort(data, 0, data.length - 1);
}
//将索引从left到right范围的数组元素进行归并排序
private static void sort(int[] data, int left, int right) {
if (left < right) {
//找出中间索引
int center = (left + right) / 2;
sort(data, left, center);
sort(data, center + 1, right);
//合并
merge(data, left, center, right);
}
}
// 将两个数组进行归并,归并前两个数组已经有序,归并后依然有序
private static void merge(int[] data, int left, int center, int right) {
int[] tempArr = new int[data.length];
int mid = center + 1;
int third = left;
int temp = left;
while (left <= center && mid <= right) {
if (data[left] - data[mid] <= 0) {
tempArr[third++] = data[left++];
}else {
tempArr[third++] = data[mid++];
}
}
while (mid <= right) {
tempArr[third++] = data[mid++];
}
while (left <= center) {
tempArr[third++] = data[left++];
}
while (temp <= right) {
data[temp] = tempArr[temp++];
}
}
}
3、冒泡排序
import java.util.Arrays;
public class BubbleSort {
public static void bubbleSort(int[] data) {
System.out.println("开始排序:");
int arrayLength = data.length;
for (int i = 0; i < arrayLength - 1; i++) {
boolean flag = false;
for (int j = 0; j < arrayLength - 1 - i; j++) {
if (data[j] > data[j + 1]) {
int temp = data[j + 1];
data[j + 1] = data[j];
flag = true;
}
}
System.out.println(Arrays.toString(data));
if (!flag)
break;
}
}
public static void main(String[] args) {
int[] data = {9, -16, 21, 23, -30, -23, 22, 24, 22, 44, 45};
System.out.println("排序之前:" + Arrays.toString(data));
bubbleSort(data);
System.out.println("排序之后:" + Arrays.toString(data));
}
}