回顾几个简单、也是时间复杂度比较高的排序算法。主要是写给自己回顾,所以不会有特别多的解释。都是最基础的排序,难度也不大。
1. 插入排序:
基本思想:在遍历数组的过程中,假设在序号 i 之前的元素即 [0..i-1] 都已经排好序,本趟需要找到 i 对应的元素 x 的正确位置 k ,并且在寻找这个位置 k 的过程中逐个将比较过的元素往后移一位,为元素 x “腾位置”,最后将 k 对应的元素值赋为 x ,一般情况下,插入排序的时间复杂度和空间复杂度分别为 O(n^2 ) 和 O(1)。
代码:
public class InsertSort {
public static void main(String[] args) {
int[] arr = { 9, 8, 7, 6, 5, 4, 3, 2, 1 };
insertSort(arr);
printArray(arr);
}
private static void insertSort(int[] arr) {
for (int i = 1; i < arr.length; i++) {
int temp = arr[i];
int j;
for (j = i - 1; j >= 0 && arr[j] > temp; j--) {
arr[j + 1] = arr[j];
}
arr[j + 1] = temp;
}
}
private static void printArray(int[] arr) {
for (int i : arr) {
System.out.print(i + " ");
}
System.out.println();
}
}
输出结果:
1 2 3 4 5 6 7 8 9
2. 冒泡排序
基本思想:依次比较两个相邻的数(泡泡),比较大小,让大的泡泡在右边,小的在左边。完成一次比较后,最小(或者最大,取决于代码)的泡泡就已经就位了。同理,重复n-1次动作完成排序。
代码:
public class BubbleSort {
public static void main(String[] args) {
int[] arr = { 9, 8, 7, 6, 5, 4, 3, 2, 1 };
bubbleSort(arr);
printArray(arr);
}
private static void bubbleSort(int[] arr) {
for (int i = 0; i < arr.length; i++) {
// 从最右边向i遍历,遍历结束,在i位置的就是最小的泡泡,当然也可以遍历到0,但是那完全没有必要,因为i之前的泡泡是已经排好序的。
for (int j = arr.length - 1; j > i; j--) {
if (arr[j] < arr[j - 1]) {
int temp = arr[j];
arr[j] = arr[j - 1];
arr[j - 1] = temp;
}
}
}
}
}
冒泡排序的思想决定了它的时间效率是很低的,时间复杂度是O(n^2)。
但是可以对冒泡算法进行一些改进,减少一些比较次数。参考博客:http://blog.youkuaiyun.com/morewindows/article/details/6657829
3. 选择排序
基本思想:选择排序的基本思想是遍历数组的过程中,以 i 代表当前需要排序的序号,则需要在剩余的 [i…n-1] 中找出其中的最小值,然后将找到的最小值与 i 指向的值进行交换。因为每一趟确定元素的过程中都会有一个选择最大值的子流程,所以人们形象地称之为选择排序。选择排序的时间复杂度和空间复杂度分别为 O(n2 ) 和 O(1) 。
代码:
public class SelectSort {
public static void main(String[] args) {
int[] arr = { 9, 8, 7, 6, 5, 4, 3, 2, 1 };
selectSort(arr);
printArray(arr);
}
private static void selectSort(int[] arr) {
for (int i = 0; i < arr.length; i++) {
int min = i;
for (int j = i + 1; j < arr.length; j++) {
if (arr[j] < arr[min]) {
min = j;
}
}
if (min > i) {
int temp = arr[i];
arr[i] = arr[min];
arr[min] = temp;
}
}
}
}