大家好呀!我是小笙,本节是我对排序算法的一个总结
各种排序算法
稳定性:一组数列在排序的时候,相同的值的相对位置是否发生变化
选择排序
概述:将某一个数列中最大的值或者最小的值与该数列的第一个进行交换,然后缩小数列范围(不包括第一个)依次反复则可以排好序
时间复杂度:o(n^2)
空间复杂度:o(1)
public class SelectionSort {
public static void main(String[] args) {
int[]nums = new int[]{
1,8,67,3,5};
sort(nums);
System.out.println(Arrays.toString(nums));
}
/**
* 选择排序 升序排序
* @param nums 数组
*/
public static void sort(int[] nums){
int len = nums.length;
if(nums == null || len < 2){
return;
}else{
for (int i = 0; i < len-1; i++) {
int minIndex = i;
for (int j = i+1; j < len; j++) {
minIndex = nums[j] < nums[minIndex]? j:minIndex;
}
int temp = nums[minIndex];
nums[minIndex] = nums[i];
nums[i] = temp;
}
}
}
}
冒泡排序
概述:类似与泡泡浮出水面,比如将最大值的值向右端浮动,浮动过程中出现左边的值大于右边的值,则需要进行交换,确保最大值最后落在最右端,依次反复
时间复杂度:o(n^2)
空间复杂度:o(1)
public class BubbleSort {
public static void main(String[] args) {
int[]nums = new int[]{
1,8,67,3,5};
sort(nums);
System.out.println(Arrays.toString(nums));
}
/**
* 冒泡排序 升序排序
* @param nums 数组
* 可以进行优化: 如果内循环一次发现没有发生交换操作,则可以认为已经排好序并跳出循环
*/
public static void sort(int[] nums){
int len = nums.length;
if(nums == null || len < 3){
return;
}else{
for (int i = len-1; i >= 0; i--) {
for (int j = 0; j < i; j++) {
if(nums[j] > nums[j+1]){
int temp = nums[j];
nums[j] = nums[j+1];
nums[j+1] = temp;
}
}
}
}
}
}
插入排序
概述:实现很像冒泡排序,注意两次循环方向,插入排序是同向的,冒泡是反向的,插入无非就是从第二数开始,插入到前面的数列中也能保持有序,在数组上的实现也就只能是层层交换,但是如果是链表可能就更好理解什么是插入概念?
时间复杂度:o(n^2)
空间复杂度:o(1)
public class InsertSort {
public static void main(String[] args) {
int[]nums = new int[]{
1,8,67,3,5};
sort(nums);
System.out.println(Arrays.toString(nums));
}
/**
* 直接插入排序 升序
* @param nums 数组
*/
public static void sort(int[] nums){
int len = nums.length;
if(nums == null || len < 2){
return;
}else{
for (int i = 1; i < len; i++) {
// 注意:看起来像冒泡,但是因为数组插入的时候, ,所以通过比较前移来实现也是一样的效果
for(int j = i;j >= 0 && nums[j] < nums[j-1];j--){
int temp = nums[j];
nums[j] = nums[j-1];
nums[j-1] = temp;
}
}
}
}
}
希尔排序
希尔排序实质上是一种分组插入方法,它的基本思想是: 对于n个待排序的数列,取一个小于n的整数step(step被称为步长)将待排序元素分成若干个组子序列,所有距离为step的倍数的记录放在同一个组中;然后,对各组内的元素进行直接插入排序。 这一趟排序完成之后,每一个组的元素都是有序的。然后减小step的值,并重复执行上述的分组和排序。重复这样的操作,当step=1时,整个数列就是有序的
时间复杂度:希尔排序的时间复杂度与增量(即,步长step的选取有关。例如,当增量为1时,希尔排序退化成了直接插入排序,此时的时间复杂度为o(N²),而Hibbard增量的希尔排序的时间复杂度为o(N3/2)
空间复杂度:o(1)
public class ShellSort {