1. 插入排序(insertion-sort):
????????????????????????????????????????? 是一種簡單直觀的排序算法。它的工作原理是通過構建有序序列,對于未排序數(shù)據(jù),在已排序序列中從后向前掃描,找到相應位置并插入
??? 算法穩(wěn)定性:
??????????????????????? 對于兩個相同的數(shù),經(jīng)過排序后,他們依舊保持之前的順序,二者次序沒有發(fā)生變化。插入排序是算法穩(wěn)定的
?? 時間復雜度:
??????? 最優(yōu)情況
????????????????????? 在插入排序中,當待排序數(shù)組是有序時,是最優(yōu)的情況,只需當前數(shù)跟前一個數(shù)比較一下就可以了,這時一共需要比較N- 1次,時間復雜度為O(n)
??????? 最壞情況
????????????????????????? 最壞的情況是待排序數(shù)組是逆序的,此時需要比較次數(shù)最多,總次數(shù)記為:1+2+3+…+N-1,所以,插入排序最壞情況下的時間復雜度為O()?
???? 動態(tài)圖:
文章來源:http://www.zghlxwxcb.cn/news/detail-697027.html
? 遞歸代碼:文章來源地址http://www.zghlxwxcb.cn/news/detail-697027.html
package com.nami.algorithm.study.day06;
import java.util.Arrays;
/**
* beyond u self and trust u self.
*
* @Author: lbc
* @Date: 2023-09-05 15:36
* @email: 594599620@qq.com
* @Description: keep coding
*/
public class InsertionSort {
/**
* 插入排序:
* 從右向左找
*
* @param target
*/
public static void sort(int[] target) {
insertion(target, 1);
}
/**
* 遞歸 縮小結果集
*
* @param target
* @param lowIndex
*/
private static void insertion(int[] target, int lowIndex) {
if (lowIndex == target.length) {
return;
}
int t = target[lowIndex];
// 已排序區(qū)域指針
int i = lowIndex - 1;
// 沒有找到插入位置
while (i >= 0 && target[i] > t) {
target[i + 1] = target[i];
i--;
// 如果到達數(shù)組0時候 依舊沒有找到,則退出循環(huán)
// 抽出,合并到while內
// if(i < 0) {
// break;
// }
}
//插入位置找到了
// 優(yōu)化減少不必要的賦值動作,
// 需要替換的數(shù)組值,正好是大于i, i+1索引的值不需要動,這個賦值動作就不必要了
if (i + 1 != lowIndex) {
target[i + 1] = t;
}
insertion(target, lowIndex + 1);
}
/**
* 兩種寫法,這種賦值次數(shù)更多
* 時間復雜度相同
* 但是 效率沒有上面的高,消耗在更多的賦值操作上了
*
* @param target
* @param lowIndex
*/
private static void insertion0(int[] target, int lowIndex) {
if (lowIndex == target.length) {
return;
}
// 已排序區(qū)域指針
int i = lowIndex - 1;
// 沒有找到插入位置
while (i >= 0 && target[i] > target[i + 1]) {
int temp = target[i];
target[i] = target[i + 1];
target[i + 1] = temp;
i--;
}
insertion(target, lowIndex + 1);
}
public static void main(String[] args) {
int[] test = new int[]{1, 54, 234, 675, 32432, 23, 78, 459, 354, 9, 344, 22, 46, 85, 236, 3278, 245, 83, 154, 2, 1, 34, 73, 23};
int[] test2 = new int[]{2, 4, 7, 3, 2, 1};
// sort(test, test.length);
sort(test);
System.out.println(Arrays.toString(test));
}
}
到了這里,關于算法 數(shù)據(jù)結構 遞歸插入排序 java插入排序 遞歸求解插入排序算法 如何用遞歸寫插入排序 插入排序動圖 插入排序優(yōu)化 數(shù)據(jù)結構(十)的文章就介紹完了。如果您還想了解更多內容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關文章,希望大家以后多多支持TOY模板網(wǎng)!