1、冒泡排序
import java.util.Arrays;
public class 冒泡排序 {
public static void main(String[] args) {
int[] arr = {1,4,2,6,3};
bubbleSort2(arr);
System.out.println(Arrays.toString(arr));
}
public static void bubbleSort(int[] arr) {
for (int i = 0; i < arr.length-1; i++) {
boolean isSorted = false;
for(int j = 0; j < arr.length - 1 -i; j++) {
if (arr[j] > arr[j+1]) {
int temp = arr[j];
arr[j] = arr[j+1];
arr[j+1] = temp;
isSorted = true;
}
}
if (!isSorted) {
break;
}
}
}
public static void bubbleSort2(int[] arr) {
int index = arr.length - 1;
for (int i = 0; i < arr.length - 1; i++) {
System.out.println("比较轮数" + i);
if (index == 0) {
break;
}
int lastSwap = 0;
for (int j = 0; j < index; j++) {
if (arr[j] > arr[j+1]) {
int temp = arr[j];
arr[j] = arr[j+1];
arr[j+1] = temp;
lastSwap = j;
}
}
index = lastSwap;
}
}
}
2、选择排序
import java.util.Arrays;
public class 选择排序 {
public static void main(String[] args) {
int[] arr = {1,4,2,6,3};
chooseSort(arr);
System.out.println(Arrays.toString(arr));
}
public static void chooseSort(int[] arr) {
for (int i = 0; i < arr.length - 1; i++) {
int minIndex = i;
for (int j = minIndex + 1; j < arr.length; j++) {
if (arr[minIndex] > arr[j]) {
minIndex = j;
}
}
if (i != minIndex) {
swap(arr, i, minIndex);
}
}
}
public static void swap(int[] arr, int i, int j) {
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}