特别奇怪的返回值
BinTa 2013-09-15 09:01:26 #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
-----------------------------------------------------
在线求大神帮助