mixpplus
8/28/2019 - 12:36 PM

## 常见的五中排序算法

``````package com.ingin.bullsort.jiecheng;

import java.util.Arrays;

public class SortDemo {
public static void main(String[] args) {
int[] arr = {1, 6, 2, 8, 9, 2};
bubbleSort(arr);
System.out.println(Arrays.toString(arr));
System.out.println("-----------------------");
int[] arr1 = {1, 6, 2, 8, 9, 2};
quickSort(arr1, 0, arr.length - 1);
System.out.println(Arrays.toString(arr1));
System.out.println("----------------------");
int[] arr2 = {1, 6, 2, 8, 9, 2};
selectSort(arr2);
System.out.println(Arrays.toString(arr2));
System.out.println("---------------------");
int[] arr3 = {1, 6, 2, 8, 9, 2};
insertSort(arr3);
System.out.println(Arrays.toString(arr3));
System.out.println("---------------------------");
int[] arr4 = {1, 6, 2, 8, 9, 2};
shellSort(arr4);
System.out.println(Arrays.toString(arr4));

}

public static void bubbleSort(int[] arr) {
for (int i = 0; i < arr.length - 1; i++) {
boolean isSorted = true;
for (int j = 0; j < arr.length - 1 - i; j++) {
if (arr[j] > arr[j + 1]) {
isSorted = false;
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
if (isSorted) {
return;
}
}
}

public static void quickSort(int[] arr, int low, int high) {
if (low >= high) {
return;
}

int left = low;
int right = high;
int key = arr[left];
while (left < right && arr[right] >= key) {
right--;
}
arr[left] = arr[right];
while (left < right && arr[left] <= key) {
left++;
}
arr[right] = arr[left];
arr[left] = key;
quickSort(arr, low, left - 1);
quickSort(arr, left + 1, high);
}

public static void selectSort(int[] arr) {
for (int i = 0; i < arr.length - 1; i++) {
int min = i;
for (int j = i + 1; j < arr.length; j++) {
if (arr[min] > arr[j]) {
min = j;
}
}
int temp = arr[min];
arr[min] = arr[i];
arr[i] = temp;
}
}

public static void insertSort(int[] arr) {
for (int i = 1; i < arr.length; i++) {
int current = arr[i];
int position = i;
while (position > 0 && arr[position - 1] > current) {
arr[position] = arr[position - 1];
position--;
}
arr[position] = current;
}
}

public static void shellSort(int[] arr) {
int step = arr.length / 2;
while (step > 0) {
for (int i = step; i < arr.length; i++) {
while (i >= step && arr[i-step] > arr[i]){
int temp = arr[i-step];
arr[i-step] = arr[i];
arr[i] = temp;
i -= step;
}
}
step /= 2;
}
}
}
``````