《算法导论》练习题--插入排序

习题:

2.1-1  以图2.2为模型,说明INSERTION-SORT在数组A=<31,41,59,26,41,58>上的执行过程


using System;
using System.Collections.Generic;


namespace InsertSort
{
    class Program
    {
        static void Main(string[] args)
        {
            Sort();
        }

        private static void Sort()
        {
            Console.WriteLine("插入排序");
            int[] arr = {31,41,59,26,41,58 };
            Console.Write("排序前数组:");
            foreach (int i in arr)
            {
                Console.Write(i+" ");
            }
            Console.WriteLine();
            var length = arr.Length;
            for (int i = 1; i < length; i++)
            {
                for (int j = i; j > 0; j--)
                {
                    if (arr[j-1]> arr[j])
                    {
                        arr[j - 1] = arr[j] ^ arr[j - 1];
                        arr[j] = arr[j] ^ arr[j - 1];
                        arr[j - 1] = arr[j] ^ arr[j - 1];
                    }
                }
                PrintResult(arr);
            }
        }

        private static void PrintResult(IEnumerable<int> arr)
        {
            foreach (int i in arr)
            {
                Console.Write(i+" ");
            }
            Console.WriteLine();
        }

    }
}

运行结果:



2.1-4  考虑把两个n位二进制整数加起来的问题,这两个整数分别存储在两个n元数组A和B中。这两个整数的和应按二进制形式存储在一个(n+1)元数组C中。请给出该问题的形式化描述,并写出伪代码。


using System;
using System.Collections.Generic;

namespace Binary
{
    class Program
    {
        const int NUM = 8;
        static void Main(string[] args)
        {
            BinaryAdd();
        }
        private static void BinaryAdd()
        {
            int[] a = new int[NUM] { 1, 1, 0, 1, 0, 1, 0, 1 };//213
            int[] b = new int[NUM] { 1, 0, 0, 1, 1, 1, 0, 1 };//157
            int[] c = new int[NUM + 1];
            int flag = 0;//进位标识
            for (int i = NUM; i > 0; --i)
            {
                c[i] = a[i - 1] + b[i - 1] + flag;
                if (c[i] > 1)//1或2
                {
                    c[i] = c[i] % 2;
                    flag = 1;
                }
                else
                {
                    flag = 0;
                }
            }
            c[0] = flag;
            foreach (int i in c)
            {
                Console.Write(i);
            }
        }
    }
}

运行结果:



  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值