資料結構精要------直接插入排序和希爾排序演算法

來源:互聯網
上載者:User

標籤:資料結構   排序演算法   希爾排序   插入排序   

上篇總結中主要實踐了演算法的內排序的選擇排序,那麼接下來我們繼續實踐插入排序排序的兩種:直接插入排序和希爾排序演算法。

-----直接插入排序

package com.sort;/** * 直接插入排序 *  * @author weixing-yang *  * 演算法思路: *  每步將一個待排序的元素,插入到前面已排序好的一組元素中的適當位置,  *  直到所有元素全部出入完成為止。 */public class InsertionSort {public void insertionSort(int[] arr, int n) {for (int i = 1; i < n - 1; i++) {int temp = arr[i];//取得第二個元素if (temp < arr[i - 1]) {int j;for (j = i-1; j >= 0 && arr[j] > temp; j--) {arr[j+1] = arr[j];}arr[j+1] = temp;}}}}
----- 希爾排序

希爾排序(Shell Sort)是插入排序的一種,是將整個無序列分割成若干小的子序列分別進行插入排序。

package com.sort;/** * 希爾排序 * @author weixing-yang * *演算法思路 *先取出一個正整數d1<n,把所有序號相隔d1的元素分別放置一個組中,各組內進行直接插入排序。 *  然後在取d2<d1,重複上述分組和排序操作。直至di =1,即所有記錄放到一組中排序為止。 *   */public class ShellSort {public void shellSort(int[] arr, int n){int i,j,k,temp;k = (n-1)/2;while(k > 0){for (i = k; i < n-1; i++) {temp = arr[i];for (j = i-k; j >= 0 && arr[j] > temp; j -= k) {arr[j+k] = arr[j];}arr[j+k] = temp;}k/=2;}}}
-----測試函數

package com.sort;public class Main {public static void main(String[] args){int[] array = {36, 25, 45,40, 12, 34, 55}; int n = array.length;InsertionSort insert = new InsertionSort();ShellSort shell = new ShellSort();long start = System.currentTimeMillis();//insert.insertionSort(array, n);shell.shellSort(array, n);long end = System.currentTimeMillis();long sum = end - start;System.out.println("排序花費的總毫秒數:"+sum);for (int i = 0; i < array.length; i++) {System.out.print(array[i]+" ");}}}

-----運行結果

排序花費的總毫秒數:012 25 34 36 40 45 55 

直接插入排序是穩定排序,時間複雜度是n2,希爾排序是不穩定排序。


@@------->>下篇繼續實踐歸併排序的兩種排序演算法。



聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.