冒泡
每次冒泡把最大值冒泡到最后,尾部的数组就是有序的
插入
把需要插入的数据插入有序的数组中,找到合适的位置,把比它大的数据后移一位,并把数据插入这个合适的位置
选择
每次找出最小值,把最小值设置到未排序数组最前面
示例
package sort;
import java.util.Arrays;
public class SimpleSort {
/**
* 冒泡排序 每次把最大值的冒泡到最后
*/
public static void bubbleSort(int[] array) {
int size = array.length;
if (size <= 1) {
return;
}
for (int i = 0; i < size; i++) {
boolean isSort = false;
for (int j = 0; j < size - i - 1; j++) {
if (array[j] > array[j + 1]) {
int temp = array[j];
array[j] = array[j + 1];
array[j + 1] = temp;
isSort = true;
}
}
if (!isSort) {
break;
}
}
}
/**
* 插入排序 在有序的数组中插入合适的位置,把比它大的数据后移
*/
public static void insertSort(int[] array) {
int size = array.length;
if (size <= 1) {
return;
}
for (int i = 1; i < size; i++) {
//去除当前要插入的数据
int temp = array[i];
int j = i - 1;
for (; j >= 0; j--) {
//判断前面的数据是否比要插入的数据大
if (array[j] > temp) {
//迁移比它大的数据
array[j + 1] = array[j];
} else {
break;
}
}
//插入合适的位置
array[j + 1] = temp;
}
}
/**
* 选择排序
* 获取最小的值,把最小值与未排序的首位换位置
* @param array
*/
public static void selectSort(int[] array) {
int size = array.length;
if (size <= 1) {
return;
}
for (int i = 0; i < size; i++) {
int min = i;
for (int j = i + 1; j < size; j++) {
if (array[j] < array[min]) {
min = j;
}
}
if (i != min) {
int temp = array[i];
array[i] = array[min];
array[min] = temp;
}
}
}
public static void main(String[] args) {
int[] array = {2, 3, 1, 6, 4, 5};
bubbleSort(array);
System.out.println(Arrays.toString(array));
int[] array1 = {2, 3, 1, 6, 4, 5};
insertSort(array1);
System.out.println(Arrays.toString(array1));
int[] array2 = {2, 3, 1, 6, 4, 5};
selectSort(array2);
System.out.println(Arrays.toString(array2));
}
}
网友评论