要用C++是实现起来是很困难的,因为需要用到几大块的小算法,才能实现。
第一是行间排序,第二是行列变换,第三是前后移动元素,这些算法都组合起来,整个过程就变得很复杂了。
这次我是用二维数组来实现的,也可以用vector实现同样的效果,感觉能用vector还是用vector吧。而且我把书中的列排序,改变成行排序了,因为C++的习惯还是行优先数组。
下面是整个程序,程序还是挺大的,相对于一个普通算法来说的话。所以写这个程序也要很耐心,要有时间。
#includeusing namespace std; const int COLUMNS = 18; const int ROWS = 3; template void compareExchange(T& a, int i, int j) { if(a[i]>a[j]) swap((a[i]), (a[j])); //cout< void insertionSort(T& a, int n) { for(int j=1; j =0; i--) { compareExchange(a, i, i+1); } } template void rowSort(T (&a)[ROWS][COLUMNS]) { int s=ROWS, c=COLUMNS; //Handle the enter data, make sure it fit this algorithm requirements bool flag = true; if((c%2) != 0) { cerr<<"Error: Columns c must be even!"< =2*s*s)) { cerr<<"Warning: Columns c should be >= rows 2*s*s, " <<"or you may not get the correct answer!"<
总结:
个人觉得能不用普通c数组还是不要用普通数组,因为下标,内存处理等都非常麻烦,非常耗时。还是用vector等STL的标准容器会大大减少出错的几率。
逻辑问题也很重要,一不留神逻辑上就会出错,即便是能运行,那么结果也是不正确的,这样debug会花费很多时间。