实现插入排序:
图片来源:https://www.runoob.com/w3cnote/insertion-sort.html
package com.miracle.study.sort;
import org.junit.jupiter.api.Test;
import java.util.Arrays;
/**
* @author Miracle
* @date 2021/4/5 22:17
*/
public class InsertionSort {
public void sort(int[] A){
for (var i = 1; i < A.length; i++){
var j = i;
for (; j > 0 && A[j-1] > A[j]; j--){
var data1 = A[j];
var data2 = A[j-1];
A[j] = data2;
A[j-1] = data1;
}
}
Arrays.stream(A).forEach(e -> System.out.println(e));
}
@Test
public void test(){
var a = new int[]{9,1,7,3,2,5};
sort(a);
}
}
实现选择排序:
图片来源:https://www.runoob.com/w3cnote/selection-sort.html
package com.miracle.study.sort;
import org.junit.jupiter.api.Test;
import java.util.Arrays;
/**
* @author Miracle
* @date 2021/4/5 22:44
*/
public class SelectionSort {
public void sort(int[] A){
for (var i = 0; i < A.length - 1; i++){
var j = i + 1;
var min = i;
for (; j < A.length; j++){
if (A[j] < A[min]){
min = j;
}
}
var max = A[i];
A[i] = A[min];
A[min] = max;
}
Arrays.stream(A).forEach(e -> System.out.println(e));
}
@Test
public void test(){
sort(new int[]{1,5,8,3,7,9,2});
}
}
实现冒泡排序
图片来源:https://www.runoob.com/w3cnote/bubble-sort.html
package com.miracle.study.sort;
import org.junit.jupiter.api.Test;
import java.util.Arrays;
/**
* @author Miracle
* @date 2021/4/5 23:11
*/
public class BubbleSort {
public void sort(int[] sortData){
for (var i = sortData.length - 1; i >= 0; i--){
for (var j = 0; j < i; j++){
if (sortData[j] > sortData[j+1]){
var a = sortData[j];
sortData[j] = sortData[j+1];
sortData[j+1] = a;
}
}
}
Arrays.stream(sortData).forEach(e -> System.out.println(e));
}
@Test
public void test(){
var a = new int[]{9,1,7,3,2,5};
sort(a);
}
}