import java.util.Arrays;
public class Sort {
private static void insertSort(int[] array) {
if (array == null) return;
int len = array.length;
for (int i = 1; i < len; i ++) {
for (int j = i; j > 0; j --) {
if (array[j] < array[j - 1]) {
int temp = array[j];
array[j] = array[j - 1];
array[j - 1] = temp;
}
}
}
}
private static void bubbleSort(int[] array) {
if (array == null) return;
int len = array.length;
for (int i = 0; i < len; i ++) {
for (int j = 0; j < len -1 - i; j ++) {
if (array[j] > array[j + 1]) {
int temp = array[j];
array[j] = array[j + 1];
array[j + 1] = temp;
}
}
}
}
private static void selectSort(int[] array) {
if (array == null) return;
int len = array.length;
for (int i = 0; i < len ; i ++) {
for (int j = i + 1; j < len ; j ++) {
if (array[i] > array[j]) {
int temp = array[i];
array[i] = array[j];
array[j] = temp;
}
}
}
}
private static void quickSort(int[] array, int l, int r) {
if (array == null) return;
int i = l, j = r;
if (l < r) {
int temp = array[i];
while (i != j) {
while (j > i && array[j] > temp) j --;
array[i] = array[j];
while (i < j && array[i] < temp) i ++;
array[j] = array[i];
}
array[i] = temp;
quickSort(array, l, i);
quickSort(array, i + 1, r);
}
}
/**
* 创建堆,
*
* @param arr 待排序列
*/
private static void heapSort(int[] arr) {
//创建堆
for (int i = (arr.length - 1) / 2; i >= 0; i--) {
//从第一个非叶子结点从下至上,从右至左调整结构
adjustHeap(arr, i, arr.length);
}
//调整堆结构+交换堆顶元素与末尾元素
for (int i = arr.length - 1; i > 0; i--) {
//将堆顶元素与末尾元素进行交换
int temp = arr[i];
arr[i] = arr[0];
arr[0] = temp;
//重新对堆进行调整
adjustHeap(arr, 0, i);
}
}
/**
* 调整堆
*
* @param arr 待排序列
* @param parent 父节点
* @param length 待排序列尾元素索引
*/
private static void adjustHeap(int[] arr, int parent, int length) {
//将temp作为父节点
int temp = arr[parent];
//左孩子
int lChild = 2 * parent + 1;
while (lChild < length) {
//右孩子
int rChild = lChild + 1;
// 如果有右孩子结点,并且右孩子结点的值大于左孩子结点,则选取右孩子结点
if (rChild < length && arr[lChild] < arr[rChild]) {
lChild++;
}
// 如果父结点的值已经大于孩子结点的值,则直接结束
if (temp >= arr[lChild]) {
break;
}
// 把孩子结点的值赋给父结点
arr[parent] = arr[lChild];
//选取孩子结点较大的结点,继续向下筛选
parent = lChild;
lChild = 2 * lChild + 1;
}
arr[parent] = temp;
}
public static void main(String[] args) {
int[] array = {5,8,23,1,53,98,12,67,33,99,18};
insertSort(array);
System.out.println("insertSort == " + Arrays.toString(array));
bubbleSort(array);
System.out.println("bubbleSort == " + Arrays.toString(array));
selectSort(array);
System.out.println("selectSort == " + Arrays.toString(array));
quickSort(array, 0 , array.length - 1);
System.out.println("quickSort == " + Arrays.toString(array));
}
}
java 常见排序 插入排序 冒泡排序 选择排序 快速排序
于 2019-01-27 14:12:42 首次发布