您好,登錄后才能下訂單哦!
這篇文章主要為大家展示了“web中如何實(shí)現(xiàn)插入排序”,內(nèi)容簡而易懂,條理清晰,希望能夠幫助大家解決疑惑,下面讓小編帶領(lǐng)大家一起研究并學(xué)習(xí)一下“web中如何實(shí)現(xiàn)插入排序”這篇文章吧。
插入排序,一般也被稱為直接插入排序。對于少量元素的排序,它是一個(gè)有效的算法 。插入排序是一種最簡單的排序方法,插入排序和冒泡排序一樣,也有一種優(yōu)化算法,叫做拆半插入,下面為大家詳細(xì)講解一下插入排序。
將第一待排序序列第一個(gè)元素看做一個(gè)有序序列,把第二個(gè)元素到最后一個(gè)元素當(dāng)成是未排序序列。
從頭到尾依次掃描未排序序列,將掃描到的每個(gè)元素插入有序序列的適當(dāng)位置。(如果待插入的元素與有序序列中的某個(gè)元素相等,則將待插入元素插入到相等元素的后面。)
實(shí)例
function insertionSort(arr) { var len = arr.length; var preIndex, current; for (var i = 1; i while(preIndex >= 0 && arr[preIndex] > current) { arr[preIndex+1] = arr[preIndex]; preIndex--; } arr[preIndex+1] = current; } return arr; }
實(shí)例
def insertionSort(arr): for i in range(len(arr)): preIndex = i-1 current = arr[i] while preIndex >= 0 and arr[preIndex] > current: arr[preIndex+1] = arr[preIndex] preIndex-=1 arr[preIndex+1] = current return arr
實(shí)例
func insertionSort(arr []int) []int { for i := range arr { preIndex := i - 1 current := arr[i] for preIndex >= 0 && arr[preIndex] > current { arr[preIndex+1] = arr[preIndex] preIndex -= 1 } arr[preIndex+1] = current } return arr }
實(shí)例
public class InsertSort implements IArraySort { @Override public int[] sort(int[] sourceArray) throws Exception { // 對 arr 進(jìn)行拷貝,不改變參數(shù)內(nèi)容 int[] arr = Arrays.copyOf(sourceArray, sourceArray.length); // 從下標(biāo)為1的元素開始選擇合適的位置插入,因?yàn)橄聵?biāo)為0的只有一個(gè)元素,默認(rèn)是有序的 for (int i = 1; i while (j > 0 && tmp if (j != i) { arr[j] = tmp; } } return arr; } }
實(shí)例
function insertionSort($arr) { $len = count($arr); for ($i = 1; $i $len; $i++) { $preIndex = $i - 1; $current = $arr[$i]; while($preIndex >= 0 && $arr[$preIndex] > $current) { $arr[$preIndex+1] = $arr[$preIndex]; $preIndex--; } $arr[$preIndex+1] = $current; } return $arr; }
實(shí)例
void insertion_sort(int arr[], int len){ int i,j,key; for (i=1;i=0) && (arr[j]>key)) { arr[j+1] = arr[j]; j--; } arr[j+1] = key; } }
實(shí)例
void insertion_sort(int arr[],int len){ for(int i=1;iwhile((j>=0) && (key
實(shí)例
public static void InsertSort(int[] array) { for(int i = 1;i for(int j = i - 1;j >= 0;j--) { if(array[j] > temp) { array[j + 1] = array[j]; array[j] = temp; } else break; } } }
實(shí)例
for i in 1..let temp = arr[i] for j in (0..reversed() { if arr[j] > temp { arr.swapAt(j, j+1) } } }
以上是“web中如何實(shí)現(xiàn)插入排序”這篇文章的所有內(nèi)容,感謝各位的閱讀!相信大家都有了一定的了解,希望分享的內(nèi)容對大家有所幫助,如果還想學(xué)習(xí)更多知識,歡迎關(guān)注億速云行業(yè)資訊頻道!
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。