Data Structures with C++ Using STL Chapter 3算法概述---笔记
3.1
选择排序算法
算法从位置0开始,判断表中最小元素的下标。一旦找到最小元素,就把这个元素与arr[0]的内容进行交换。这一步把最小的元素放在arr[0]中,而表中的其他元素则处于无序状态。接着移动到位置1,判断子表arr[1] ... arr[n-1]中最小元素的位置,完成交换后,前两个位置的元素是有序的,接着对位置2到n-2重复这个过程。在位置n-1处不进行选择,这是因为arr[n-1]是最大的元素。选择排序算法包括n-1次重复操作,即n-1遍,因为每次操作都遍历子表的元素,并找出最小元素的下标。
void selectionSort(int arr[], int n) { int smallIndex; int pass,j; int temp; //pass的范围是0-n-2 for(pass = 0;pass < n-1; pass++) { //从下标pass开始扫描子表 smallIndex = pass; //j遍历子表arr[pass+1]到arr[n-1] if(arr[j] < arr[smallIndex]) smallIndex = j; //如果smallIndex和pass不在相同位置 //将子表中的最小项与arr[pass]交换 if(smallIndex != pass) { temp = arr[pass]; arr[pass] = arr[smallIndex]; arr[smallIndex] = temp; } } }
3.2
二分查找
int binSearch(const int arr[], int first, int last, int tatget) { int mid; //中间点的下标 int midValue; //赋值arr[mid]的对象 int origLast = last; //保存last的原始值 while(first < last) //测试非空子表 { mid = (first+last)/2; midValue = arr[mid]; if(target == midValue) return mid; //有一个匹配 //确定要查找那个子表 else if(target < minValue) last = mid; //查找 else first = mid+1; //查找子表的后半部分,重新设置first } return origLast; //没有找到目标
3.5
//一个模板类型的参数表 template <typename T> //多个模板类型的参数表 template <typename T,typename u,typename v, ....>
函数参数表至少一个参数为模板类型T,函数体中的C++语句可以使用类型T对象,但只能使用对应于类型T的实际类型有效操作。
template<typename T> T max(const T& a,const T& b) { return a < b ? b : a; }
3.7
汉诺塔难题
void hanoi(int n,const string& initNeedle,const string& endNeedle,const string& endNeedle,const string& tempNeedle) { //停止条件:移动一个盘子 if(n == 1) cout << "move" << initNeedle << "to " << endNeedle << endle; else { //从initNeedle到timpNeedle移动n-1个盒子,使用endNeedle进行临时存储 hanoi(n-1,initNeedle,tempNeedle,endNeedle); //移动最大的盘子到endNeedle cout << "move"<<initNeedle << "to"<< endNeedle <<endl; //从tempNeedle到endNeedle移动n-1个盘子,使用initNeedle进行临时存储 hanoi(n-1.temNeedle.endNeedle.initNeedle); } }
递归的算法复杂度是指数级的,迭代版本的斐波纳契数列对于n=35,迭代34次,递归则要29 860 703次

浙公网安备 33010602011771号