部分排序算法总结
1.简化版桶排序
public class Sort {
public static void main(String[] args) {
@SuppressWarnings("resource")
Scanner sc = new Scanner(System.in);
System.out.println("请输入个数:");
int number = sc.nextInt();
int[] sort = new int[number];
for (int i = 0; i < number; i++) {
sort[i] = sc.nextInt();
}
BucketSort(sort);
}
/**
* 桶排序
* @param sort
*/
public static void BucketSort(int[] sort) {
int[] bucket = new int[100];
for (int i = 0; i < sort.length; i++) {
bucket[sort[i]]++;
}
for (int i = 0; i < bucket.length; i++) {
for (int j = 0; j < bucket[i]; j++) {
System.out.println(i);
}
}
}
}
代码在读入待排序数时循环了n次,排序时循环了桶的个数m次,最终打印数据时循环了m+n次,最终的时间复杂度为O(2*(m+n)),忽略常数,复杂度为O(m+n)。
2.冒泡排序
虽然简化版的桶排序的时间复杂度很低,但是它仅仅可以对整数进行排序,而且非常浪费空间,当桶排序解决不了问题时,需要我们来学习新的排序算法:冒泡排序
基本思想:每次比较两个相邻的元素,如果它们的顺序错误就把它们交换过来。
public class Sort {
public static void main(String[] args) {
@SuppressWarnings("resource")
Scanner sc = new Scanner(System.in);
System.out.println("请输入个数:");
int number = sc.nextInt();
int[] sort = new int[number];
for (int i = 0; i < number; i++) {
sort[i] = sc.nextInt();
}
BubbleSort(sort);
int left = 0;
int right = sort.length - 1;
FastSort(sort, left, right);
for (int i : sort) {
System.out.println(i);
}
}
/**
* 冒泡排序
* @param sort
*/
public static void BubbleSort(int[] sort) {
for (int i = 0; i < sort.length; i++) {
// 不-1 sort[j + 1]数组越界
for (int j = 0; j < sort.length - i - 1; j++) {
if (sort[j] > sort[j + 1]) {
int n = sort[j];
sort[j] = sort[j + 1];
sort[j + 1] = n;
}
}
}
}
}
冒泡排序的排序部分是一个双重嵌套循环,它的时间复杂度为O(N*N)。它虽然通过比较实现了排序,但是它的时间复杂度让人望而却步,我们需要一个更简单的排序算法。
3.快速排序
public class Sort {
public static void main(String[] args) {
@SuppressWarnings("resource")
Scanner sc = new Scanner(System.in);
System.out.println("请输入个数:");
int number = sc.nextInt();
int[] sort = new int[number];
for (int i = 0; i < number; i++) {
sort[i] = sc.nextInt();
}
int left = 0;
int right = sort.length - 1;
FastSort(sort, left, right);
for (int i : sort) {
System.out.println(i);
}
}
/**
* 快速排序,既不浪费时间,也不浪费空间
* @param sort
* @param left
* @param right
*/
public static void FastSort(int[] sort, int left, int right) {
int i, j, temp;
if (left > right) {
return;
}
temp = sort[left];
i = left;
j = right;
while (i != j) {
// 首先,从后往前比较
while (sort[j] >= temp && i < j) {
j--;
}
// 从前往后比较
while (sort[i] <= temp && i < j) {
i++;
}
if (i < j) {
int n = sort[i];
sort[i] = sort[j];
sort[j] = n;
}
}
// 基准数归位
sort[left] = sort[i];
sort[i] = temp;
// 此时第一次循环比较结束,关键值的位置已经确定了。
// 左边的值都比关键值小,右边的值都比关键值大,
// 但是两边的顺序还有可能是不一样的,进行下面的递归调用
// 递归
if (i > left)
FastSort(sort, left, i - 1);// 左边序列。第一个索引位置到关键值索引-1
if (j < right)
FastSort(sort, j + 1, right);// 右边序列。从关键值索引+1到最后一个
}
}
相较于冒泡排序,快速排序的每次交换都是跳跃式的,每次排序都会设置一个基准点,以它为中心交换,减少了比较和交换次数,它的平均时间复杂度为O(NlogN)。