《算法导论》练习题--插入排序
2014-08-10 11:35
309 查看
习题:
2.1-1 以图2.2为模型,说明INSERTION-SORT在数组A=<31,41,59,26,41,58>上的执行过程
运行结果:
2.1-4 考虑把两个n位二进制整数加起来的问题,这两个整数分别存储在两个n元数组A和B中。这两个整数的和应按二进制形式存储在一个(n+1)元数组C中。请给出该问题的形式化描述,并写出伪代码。
运行结果:
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); } } } }
运行结果:
相关文章推荐
- 算法导论-插入排序
- 算法导论 插入排序 C++实现
- 算法导论--python--插入排序
- 算法导论 练习题 6.5-7
- 《算法导论》读书笔记--第二章 2.1 插入排序
- 算法导论 练习题 13.3-6
- 算法导论 练习题 14.1-6
- 算法导论——JAVA实现“插入排序”算法
- 二分法实现插入排序,时间复杂度O(nlgn),算法导论练习2.3,linux纯C实现
- 《算法导论》练习题2.1-4————二进制整数相加
- 《算法导论的Java实现》 1_1.1 插入排序
- 算法导论笔记1——插入排序
- 算法导论 练习题 6.3-2
- 算法导论 练习题 7.1-2
- 算法导论 练习题 8.1-4
- [牛客]插入排序练习题
- 算法导论 练习题 10.4-2
- 算法导论 练习题 13.1-4
- 算法导论 练习题 13.2-3
- 算法导论 练习题 14.1-7(逆序对)