插入排序
package com.nobody.sort;
public class Code01_InsertionSort {
public static void insertionSort(int[] arr) {
if (null == arr || arr.length < 2) {
return;
}
for (int i = 1; i < arr.length; i++) {
for (int j = i - 1; j >= 0 && arr[j] > arr[j + 1]; j--) {
swap(arr, j, j + 1);
}
}
}
private static void swap(int[] arr, int i, int j) {
arr[i] = arr[i] ^ arr[j];
arr[j] = arr[i] ^ arr[j];
arr[i] = arr[i] ^ arr[j];
}
}
选择排序
package com.nobody.sort;
public class Code02_SelectionSort {
public static void selectionSort(int[] arr) {
if (null == arr || arr.length < 2) {
return;
}
for (int i = 0; i < arr.length - 1; i++) {
int minIndex = i;
for (int j = i + 1; j < arr.length; j++) {
minIndex = arr[j] < arr[minIndex] ? j : minIndex;
}
if (i != minIndex) {
swap(arr, i, minIndex);
}
}
}
private static void swap(int[] arr, int i, int j) {
arr[i] = arr[i] ^ arr[j];
arr[j] = arr[i] ^ arr[j];
arr[i] = arr[i] ^ arr[j];
}
}
冒泡排序
package com.nobody.sort;
public class Code03_BubbleSort {
public static void bubbleSort(int[] arr) {
if (null == arr || arr.length < 2) {
return;
}
for (int i = arr.length - 1; i > 0; i--) {
for (int j = 0; j < i; j++) {
if (arr[j] > arr[j + 1]) {
swap(arr, j, j + 1);
}
}
}
}
private static void swap(int[] arr, int i, int j) {
arr[i] = arr[i] ^ arr[j];
arr[j] = arr[i] ^ arr[j];
arr[i] = arr[i] ^ arr[j];
}
}
测试
package com.nobody.sort;
import java.util.Arrays;
public class Main {
public static void main(String[] args) {
int[] arr = {1, 5, 3, 2, 8, 10, 11, 3, 4, 0};
System.out.print("原始数组:");
Arrays.stream(arr).forEach(e -> System.out.print(e + " "));
System.out.println();
Code01_InsertionSort.insertionSort(arr);
System.out.print("插入排序:");
Arrays.stream(arr).forEach(e -> System.out.print(e + " "));
System.out.println();
int[] arr1 = {1, 5, 3, 2, 8, 10, 11, 3, 4, 0};
Code02_SelectionSort.selectionSort(arr1);
System.out.print("选择排序:");
Arrays.stream(arr1).forEach(e -> System.out.print(e + " "));
System.out.println();
int[] arr2 = {1, 5, 3, 2, 8, 10, 11, 3, 4, 0};
Code03_BubbleSort.bubbleSort(arr2);
System.out.print("冒泡排序:");
Arrays.stream(arr2).forEach(e -> System.out.print(e + " "));
System.out.println();
}
}
测试结果
原始数组:1 5 3 2 8 10 11 3 4 0
插入排序:0 1 2 3 3 4 5 8 10 11
选择排序:0 1 2 3 3 4 5 8 10 11
冒泡排序:0 1 2 3 3 4 5 8 10 11