
题目
解决代码及点评
/* 给定一个存放整数的数组,重新排列数组使得数组左边为奇数,右边为偶数 解决方法: 两边同时遍历,如果遇到左边偶数或者右边基数,则交换 */ #include <iostream> using namespace std; void Sort(int *pnArr, int nLen) { int i = 0; int j = nLen - 1; // 两边同时遍历 while (i < j) { // 左边基数则pass while (pnArr[i] % 2 == 1 && i < j) { i++; } // 右边偶数也pass while (pnArr[j] % 2 == 0 && i < j) { j--; } // 否则交换 swap(pnArr[i], pnArr[j]); } } int main() { int nArr[] = {1,234,23,2,1,5,7,9,34,22,45,77,54,31,34}; int nLen = sizeof(nArr) / sizeof(int); Sort(nArr, nLen); for (int i = 0; i < nLen; i++) { cout<<nArr[i]<<" "; } cout<<endl; system("pause"); return 0; }
代码下载及其运行
代码下载地址:http://download.csdn.net/detail/yincheng01/6704519
解压密码:c.itcast.cn
下载代码并解压后,用VC2013打开interview.sln,并设置对应的启动项目后,点击运行即可,具体步骤如下:
1)设置启动项目:右键点击解决方案,在弹出菜单中选择“设置启动项目”
2)在下拉框中选择相应项目,项目名和博客编号一致
3)点击“本地Windows调试器”运行
程序运行结果