习题:
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);
}
}
}
}
运行结果: