1、冒泡排序
比较相邻的元素。如果第一个比第二个大,就交换它们两个;这样共需要比较length-1轮,两两相比每一轮比较length-1-i次,每次比较出最大数
比如:
import java.util.Arrays;
public class MPPaiXu {
public static void main(String[] args) {
int[] arr ={5,3,9,12,7,8};
int len = arr.length;
for (int i = 0; i < len - 1; i++) {
for (int j = 0; j < len - 1 - i; j++) {
if (arr[j] > arr[j+1]) { // 相邻元素两两对比
int temp = arr[j+1]; // 元素交换
arr[j+1] = arr[j];
arr[j] = temp;
}
}
}
System.out.println(Arrays.toString(arr));
}
}
2、选择排序(Selection Sort)
首先在未排序序列中找到最小(大)元素,存放到排序序列的起始位置,然后,再从剩余未排序元素中继续寻找最小(大)元素,然后放到已排序序列的末尾。以此类推,直到所有元素均排序完毕
import java.util.Arrays;
public class selectionSort {
public static void main(String[] args) {
int[] arr ={5,3,9,12,7,8};
int len = arr.length;
int minIndex, temp;
for (int i = 0; i < len - 1; i++) {
minIndex = i;
for (int j = i + 1; j < len; j++) {
if (arr[j] < arr[minIndex]) { // 寻找最小的数
minIndex = j; // 将最小数的索引保存
}
}
temp = arr[i];
arr[i] = arr[minIndex];
arr[minIndex] = temp;
}
System.out.println(Arrays.toString(arr));
}
}
3、插入排序
它的工作原理是通过构建有序序列,对于未排序数据,在已排序序列中从后向前扫描,找到相应位置并插入
import java.util.Arrays;
public class insertionSort {
public static void main(String[] args) {
int[] arr ={5,2,4,3,7,9};
int len = arr.length;
int preIndex, current;
for (int i = 1; i < len; i++) {
preIndex = i - 1;
current = arr[i];
while (preIndex >= 0 && arr[preIndex] > current) {
arr[preIndex + 1] = arr[preIndex];
preIndex--;
}
arr[preIndex + 1] = current;
System.out.println(Arrays.toString(arr));
}
System.out.println(Arrays.toString(arr));
}
}