特别奇怪的返回值
#include"iostream"
#include"fstream"
using namespace std;
#define N 1000
int num;
int Partition(int* a,int left,int right)
{
int temp=a[left];
while(left<right)
{
while(a[right]>=temp&&left<right) right--;
a[left]=a[right];
while(a[left]<=temp&&left<right) left++;
a[right]=a[left];
}
a[left]=temp;
return left;
}
int find_k(int* a,int left,int right,int k)
{ int p=Partition(a,left,right);
int j=p-left+1;
if(j==k) {cout<<"a[p]:"<<a[p]<<endl;num=p;return a[p];}
if(j<k) find_k(a,p+1,right,k-j);
if(j>k) find_k(a,left,p,k);
}
int main()
{
//////////////////////////////////////
int a[N],count=-1;
ifstream file;
file.open("bs_2.txt");
if(file.good())
{
while(!file.eof())
{
file>>a[++count];
}
}
else cout<<"open file fail!"<<endl;
file.close();
int k;
cout<<"input k:";
cin>>k;
int num2=find_k(a,0,count-1,k);
cout<<"the number is:"<<num2<<endl;
system("pause");
}
我写的求“第k个小的数”的程序,特别奇怪,在find_k()函数测试,return a[p];之前我先把a[p]输出,然后函数返回值赋值给num2,同样输出在控制台,很奇怪,在函数体内输出的a[p]是正确的,但是由函数返回值得到的num2,确是一个乱数,明明都是a[p],为什么会有不同的结果呢?
----->程序排序数组来自文件bs_2.txt,内容如下:
---------------------
132 133 134 11 12 139 140 62 63 64 65 66 67
1 2 3 4 5 6 7 48 49 50 138 16 17 20
101 102 103 104 105 106 146 147 148 107 108 109 110 96
21 22 23 24 25 25 27 28 29 30
41 42 8 9 10 46 47
51 52 53 54 55 56 57 58 59 60
73 74 75 71 72 18 97 98 19 129 130
137 136 13 14 144 145 15 128
77 78 31 32 35 76 149 150 99 100 119
91 92 93 94 95 116 117 114 118 120
81 82 83 84 85 122 123
112 111 43 44 45 113 115 36 37 38 39 40 25 126 127
131 135 61 69 70
141 142 143 86 68 87 90
121 88 89 124 179 80 33 34
-----------------------------------------------------
在线求大神帮助 c++??排序
[解决办法]
试试用一个局部变量保存一下a[p]再返回,比如int temp = a[p];return temp;
[解决办法]
没看到 函授体后那里有修改的地方!
[解决办法]
在我这跑是正确的。。
[解决办法]
我跑的结果也对呢
[解决办法]
“给定一个小点的输入,完整单步跟踪(同时按Alt+7键查看Call Stack里面从上到下列出的对应从里层到外层的函数调用历史)一遍。”是理解递归函数工作原理的不二法门!
递归函数关注以下几个因素
退出条件
参数有哪些
返回值是什么
局部变量有哪些
全局变量有哪些
何时输出
会不会导致堆栈溢出