C#插入排序☞递归实现

        int[] arr = new int[] { 1, 5, 6, 9, 2, 45, 36 };//任意数组

        Recursion(arr, arr.Length - 1);
        foreach (var item in arr)
         {
            Console.WriteLine(item);
         }
        /// <summary>
        /// 递归遍历
        /// </summary>
        /// <param name="arr">数组</param>
        /// <param name="n">数组索引</param>
        public static void Recursion(int[] arr, int n)
        {
            if (n > 0)
            {
                Recursion(arr, n - 1);
                Insert(arr, n);
            }
            else
                return;
        }

        /// <summary>
        /// 插入排序
        /// </summary>
        /// <param name="arr">数组</param>
        /// <param name="n">当前索引</param>
        static void Insert(int[] arr, int n)
        {
            int i = n - 1;
            int key = arr[n];
            while ((i >= 0) && (key < arr[i]))
            {
                arr[i + 1] = arr[i];
                i--;
            }
            arr[i + 1] = key;
            return;
        }

ps:其实就是用递归代替插入排序的for循环

posted @ 2012-10-17 11:22  一抹、思乡泪  Views(603)  Comments(0Edit  收藏  举报