冒泡排序
冒泡排序时间复杂度是O(n^2),它是稳定排序算法。
/**
* 冒泡排序,从小到大排序
* 思想:将最大值挪到数组最后面,依次累推
*/
public class BubbleSort {
public static void main(String[] args) {
int array[] = {1, 23, 4, 22, 3, 11, 24, 19, 6, 11};
for (int i = 0; i < array.length; i++) {
//内层遍历,将最小(最大)数放在数组最后面
for (int j = 0; j < array.length - i - 1; j++) {
if (array[j] > array[j + 1]) {
int temp = array[j];
array[j] = array[j + 1];
array[j + 1] = temp;
}
}
}
//输出数组
for (int j : array) {
System.out.print(j + " ");
}
}
}
简单选择排序(不推荐)
选择排序时间复杂度是O(n^2),但它是不稳定排序算法。
/**
* 简单选择排序,从小到大排序
* 思想:将最小值找出来放在数组第一个位置,第二小的值放数组第二个位置,依次类推
*/
public class SelectSort {
public static void main(String[] args) {
int array[] = {1, 23, 4, 22, 3, 11, 24, 19, 6, 11};
for (int i = 0; i < array.length - 1; i++) {
int min = i;//假定第一个为最小值,记录最小值下标,方便交换数据
for (int j = i + 1; j < array.length; j++) {
if (array[j] < array[min]) {
min = j;
}
}
//将最小值放在数组最前面
if (min != i) {
int temp = array[i];
array[i] = array[min];
array[min] = temp;
}
}
//输出数组
for (int j : array) {
System.out.print(j + " ");
}
}
}
直接插入排序(推荐)
插入排序和冒泡排序的时间复杂度都是O(n^2),都是稳定排序算法,但是插入排序不存在交换元素,比冒泡少两次操作,整体上优于冒泡排序。
/**
* 直接插入排序,从小到大排序
* 思想:从下标1开始依次将数据插入到数组前面已经有序的序列中
*/
public class InsertSort {
public static void main(String[] args) {
int array[] = {1, 23, 4, 22, 3, 11, 24, 19, 6, 11};
for (int i = 1; i < array.length; i++) {
int temp = array[i];//array[i]会被覆盖,先记录下来
int j;//记录最终的下标
for (j = i; array[j - 1] > temp && j - 1 > 0; j--) {
array[j] = array[j - 1];//数据向后挪动
}
array[j] = temp;
}
//输出数组
for (int j : array) {
System.out.print(j + " ");
}
}
}
//按下面这样写也行,比较好理解,思路是一样的:
public static void main(String[] args) {
int array[] = {1, 23, 4, 22, 3, 11, 24, 19, 6, 11};
for (int i = 1; i < array.length; i++) {
int temp = array[i];//array[i]会被覆盖,先记录下来
int j = i-1;//记录最终的下标,要声明在for的外面,for后面要用到
for (;j > 0; j--) {
if(array[j] > temp) {
array[j+1] = array[j];//数据向后挪动
}else{
break;
}
}
array[j+1] = temp;//注意j要加1,因为j指定了比temp小的元素
}
//输出数组
for (int j : array) {
System.out.print(j + " ");
}
}