马上加入IBC程序猿 各种源码随意下,各种教程随便看! 注册 每日签到 加入编程讨论群

C#教程 ASP.NET教程 C#视频教程程序源码享受不尽 C#技术求助 ASP.NET技术求助

【源码下载】 社群合作 申请版主 程序开发 【远程协助】 每天乐一乐 每日签到 【承接外包项目】 面试-葵花宝典下载

官方一群:

官方二群:

C#中插入排序

  [复制链接]
查看2970 | 回复3 | 2016-11-28 09:36:58 | 显示全部楼层 |阅读模式
[C#] 纯文本查看 复制代码
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;
                }
            }
        }
    }
}

C#论坛 www.ibcibc.com IBC编程社区
C#
C#论坛
IBC编程社区
ibcadmin | 2016-11-28 09:37:10 | 显示全部楼层
111
C#论坛 www.ibcibc.com IBC编程社区
C#
C#论坛
IBC编程社区
Amy尾巴 | 2016-11-28 09:38:07 | 显示全部楼层
222
即墨还雀 | 2016-11-28 10:35:06 | 显示全部楼层
4444
*滑块验证:
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则