2.比較排序之梳排序,排序

來源:互聯網
上載者:User

2.比較排序之梳排序,排序

  梳排序的知名度遠沒有其他排序演算法那麼高,它是在冒泡排序的基礎上做的改進,引入類似“步長”以及“子序列”概念,這兩個概念在後面的排序演算法中會經常提及。

  待排序列:{10, 2, 11, 8, 7} groupNums = length = 5

  步長係數(分組係數)coefficient = 1.3

  排序過程如所示。

  Java

 1 package com.algorithm.sort; 2  3 import java.util.Arrays; 4  5 /** 6  * 梳排序 7  * Created by 餘林豐 on 2017/6/20. 8  */ 9 public class Comb {10     public static void main(String[] args) {11         int[] nums = {10, 2, 11, 8, 7};12         nums = combSort(nums);13         System.out.println(Arrays.toString(nums));14     }15     16     /**17      * 梳排序18      * @param nums 待排序數組19      * @return 排好序的數組20      */21     private static int[] combSort(int[] nums) {22         float cofficient = 1.3f;    //步長係數(分組係數) = 1.3,大量實驗獲得的最佳值23         int groupNums = nums.length;24         boolean flag = false;25         while (groupNums > 1 || flag) {26             groupNums = (int) ((groupNums / cofficient) > 1 ? (groupNums / cofficient) : 1);27             flag = false;28             for (int i = 0; i + groupNums < nums.length; i++) {29                 if (nums[i] > nums[i + groupNums]) {30                     int temp = nums[i];31                     nums[i] = nums[i + groupNums];32                     nums[i + groupNums] = temp;33                     flag = true;34                 }35             }36         }37         return nums;38     }39 }

  Python3

 1 #梳排序 2 def comb_sort(nums): 3     cofficient = 1.3        #最佳係數 4     groupNums = len(nums) 5     flag = False 6     while groupNums > 1 or flag: 7         groupNums = int(groupNums / cofficient) if (groupNums / cofficient) > 1 else 1 8         flag = False 9         for i in range(len(nums)):10             if i + groupNums >= len(nums):11                 break12             if nums[i] > nums[i + groupNums]:13                 temp = nums[i]14                 nums[i] = nums[i + groupNums]15                 nums[i + groupNums] = temp16                 flag = True17         18     return nums19 20 nums = [10, 2, 11, 8, 7]21 nums = comb_sort(nums)22 print(nums)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.