冒泡排序法
package sort;
/**
* 直接插入排序
*
* @author shkstart 2018-12-17
*/
public class InsertSort {
public static void insertSort(int[] data) {
System.out.println("开始排序");
int arrayLength = data.length;
for (int i = 1; i < arrayLength; i++) {
int temp = data[i];
if (data[i] - data[i - 1] < 0) {
int j = i - 1;
for (; j >= 0 && data[j] - temp > 0; j--) {
data[j + 1] = data[j];
}
data[j + 1] = temp;
}
System.out.println(java.util.Arrays.toString(data));
}
}
public static void main(String[] args) {
int[] data = { 9, -16, 21, 23, -30, -49, 21, 30, 30 };
System.out.println("排序之前:\n" + java.util.Arrays.toString(data));
insertSort(data);
System.out.println("排序之后:\n" + java.util.Arrays.toString(data));
}
}
快速排序
public static void main(String[] args) {
int[] arr = {9, -16, 30, 23, -30, -49, 25, 21, 30};
System.out.println("排序之前:" + java.util.Arrays.toString(arr));
quickSort(arr);
System.out.println("排序之后:" + java.util.Arrays.toString(arr));
}
public static void quickSort(int[] arr) {
subSort(arr, 0, arr.length - 1);
}
public static void subSort(int[] arr, int start, int end) {
if (start < end) {
int base = arr[start];
int low = start;
int high = end + 1;
while (true) {
while (high > start && arr[--high] >= base)
;
while (low < end && arr[++low] <= base)
;
if (low < high) {
swap(arr, low, high);
} else {
break;
}
}
swap(arr, start, high);
subSort(arr, start, high - 1);
subSort(arr, high + 1, end);
}
}
public static void swap(int[] arr, int i, int j) {
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}