国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 學院 > 開發設計 > 正文

排序算法之直接插入排序

2019-11-17 02:47:41
字體:
來源:轉載
供稿:網友
排序算法之直接插入排序直接插入排序定義:  每次從無序表中取出第一個元素,把它插入到有序表的合適位置,使有序表仍然有序。直接插入排序屬于穩定的排序,最壞時間復雜性為O(n^2),空間復雜度為O(1)。
class PRogram{    static void Main(string[] args)    {        int[] array = new[] { 234, 632, 23, 643, 2, 6, -2, 423, 2342,43 };        Console.WriteLine("排序前:");        Console.WriteLine(string.Join(",", array));        InsertSort(array);        Console.WriteLine("排序后:");        Console.WriteLine(string.Join(",", array));        Console.ReadKey();    }    /// <summary>    /// 直接插入排序    /// </summary>    /// <param name="sources">目標數組</param>    private static void InsertSort(int[] sources)    {        // 從索引1開始,假設sources[0]已經有序        for (int i = 1, len = sources.Length - 1; i <= len; i++)        {            // 準備要插入的數據            int insertValue = sources[i],            // 假設要插入的索引            insertIndex = i - 1;            // 遍歷查找插入的索引位置            while (insertIndex >= 0 && insertValue < sources[insertIndex])            {                // 當前數據后移一位                sources[insertIndex + 1] = sources[insertIndex];                insertIndex--;            }                        // 不滿足以上條件,說明找到位置,插入數據            sources[insertIndex + 1] = insertValue;        }    }        /// <summary>    /// 直接插入排序 for實現    /// </summary>    /// <param name="sources">目標數組</param>    private static void InsertSort1(int[] sources)    {        for (int i = 1, len = sources.Length - 1; i <= len; i++)        {            for (int j = i; j > 0; j--)            {                if (sources[j] > sources[j - 1]) // > 降序, < 升序                {                    int temp = sources[j];                    sources[j] = sources[j - 1];                    sources[j - 1] = temp;                }            }        }    }}


發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 永昌县| 那曲县| 阳原县| 灵宝市| 额敏县| 宁国市| 泽州县| 白银市| 武山县| 如东县| 墨玉县| 商洛市| 蓬莱市| 宁河县| 浪卡子县| 五寨县| 乌拉特后旗| 木里| 山东| 辛集市| 陆川县| 鄱阳县| 秦皇岛市| 霍邱县| 林甸县| 安塞县| 始兴县| 汶上县| 军事| 德保县| 临潭县| 南陵县| 犍为县| 图木舒克市| 白银市| 雷山县| 河西区| 都江堰市| 静宁县| 荔波县| 长丰县|