package com.java.testsort;
import java.util.Arrays;
public class SortAll {
public static void main(String[] args) {
int[] arr = {-1, 0, 9, 10, 11, 3};
int[] temp = new int[arr.length];
// maoPaoSort(arr);
// changeSort(arr);
// insertSort(arr);
// quickSort(arr, 0, arr.length - 1);
// guiBinSort(arr,0,arr.length-1,temp);
System.out.println(Arrays.toString(arr));
}
//冒泡排序
public static void maoPaoSort(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;
}
}
}
}
//选择排序
public static void changeSort(int[] arr) {
for (int i = 0; i < arr.length - 1; i++) {
for (int j = i + 1; j < arr.length; j++) {
if (arr[i] > arr[j]) {
int temp = arr[j];
arr[j] = arr[i];
arr[i] = temp;
}
}
}
}
//插入排序
public static void insertSort(int[] arr) {
for (int i = 0; i < arr.length; i++) {
int insertVal = arr[i];
int insertIndex = i - 1;
while (insertIndex >= 0 && insertVal < arr[insertIndex]) {
arr[insertIndex + 1] = arr[insertIndex];
insertIndex--;
}
arr[insertIndex + 1] = insertVal;
}
}
//快速排序
public static void quickSort(int[] arr, int left, int right) {
if (left < right) {
int l = left;
int r = right;
int temp = arr[left];
while (l < r) {
while (arr[r] > temp && l < r) {
r--;
}
if (l < r) {
arr[l] = arr[r];
l++;
}
while (arr[l] < temp && l < r) {
l++;
}
if (l < r) {
arr[r] = arr[l];
r--;
}
}
arr[l] = temp;
quickSort(arr, left, l - 1);
quickSort(arr, l + 1, right);
}
}
//归并排序
public static void guiBinSort(int[] arr, int left, int right, int[] temp) {
if (left < right) {
int mid = (left + right) / 2;
guiBinSort(arr, left, mid, temp);
guiBinSort(arr, mid + 1, right, temp);
merge(arr, left, mid, right, temp);
}
}
public static void merge(int[] arr, int left, int mid, int right, int[] temp) {
int l = left;
int j = mid + 1;
int tempIndex = 0;
while (l <= mid && j <= right) {
if (arr[l] <= arr[j]) {
temp[tempIndex++] = arr[l++];
} else {
temp[tempIndex++] = arr[j++];
}
}
while (l <= mid) {
temp[tempIndex++] = arr[l++];
}
while (j <= right) {
temp[tempIndex++] = arr[j++];
}
tempIndex = 0;
int leftIndex = left;
while (leftIndex <= right) {
arr[leftIndex++] = temp[tempIndex++];
}
}
}
各种常见排序
最新推荐文章于 2022-07-17 15:53:21 发布