这是我用c++写的,主要函数基本一样,大家可以参考一下
#include<iostream.h>
class HalfFind {
public:
HalfFind(int *a, int n);
~HalfFind();
int arraySort(int *a, int n);
int halfFind(int *a, int x1, int n);
void show();
private:
int *array;
//int x;
};
HalfFind::HalfFind(int *a, int n)
{
array = new int[n];
for(int i=0; i<n; i++)
array[i] = a[i];
}
HalfFind::~HalfFind()
{
delete []array;
}
int HalfFind::arraySort(int *a, int n) // 对数组进行排序
{
int i, j;
for(i=0; i<n; i++)
{
for(j=i+1; j<n; j++)
{
int temp;
if(a[i] > a[j])
{
temp = a[i];
a[i] = a[j];
a[j] = temp;
}
}
array[i] = a[i];
//cout << array[i] << " ";
}
return a[i];
}
int HalfFind::halfFind(int *a, int x1, int n) // 用折半查找
{
int low, hight, mid;
int flag;
low = 1;
hight = n;
flag = 0;
while (low <= hight)
{
mid = (low + hight) / 2;
if (x1 < a[mid]) // 插入应在左区间
hight = mid - 1;
else if(x1 > a[mid])
low = mid + 1; // 插入应在右区间
else
{
flag = mid;
break;
}
}
return flag;
}
void HalfFind::show()
{
int i;
for(i=0; i<15; i++)
{
cout << array[i] << " ";
}
}
void main()
{
int i;
int ob[15] = {1,3,5,8,7,4,2,6,10,11,12,13,9,15,14};
HalfFind obj(ob, 15);
cout << "输出的数组是:" << endl;
obj.show();
cout << endl;
cout << "由小到大排序:" << endl;
obj.arraySort(ob, 15);
obj.show();
cout << endl;
i = obj.halfFind(ob, 13, 15);
if (i == 0)
cout << "找不到";
else
cout << "所要找的元素的位置:" << i << endl;
}
#include<iostream.h>
class HalfFind {
public:
HalfFind(int *a, int n);
~HalfFind();
int arraySort(int *a, int n);
int halfFind(int *a, int x1, int n);
void show();
private:
int *array;
//int x;
};
HalfFind::HalfFind(int *a, int n)
{
array = new int[n];
for(int i=0; i<n; i++)
array[i] = a[i];
}
HalfFind::~HalfFind()
{
delete []array;
}
int HalfFind::arraySort(int *a, int n) // 对数组进行排序
{
int i, j;
for(i=0; i<n; i++)
{
for(j=i+1; j<n; j++)
{
int temp;
if(a[i] > a[j])
{
temp = a[i];
a[i] = a[j];
a[j] = temp;
}
}
array[i] = a[i];
//cout << array[i] << " ";
}
return a[i];
}
int HalfFind::halfFind(int *a, int x1, int n) // 用折半查找
{
int low, hight, mid;
int flag;
low = 1;
hight = n;
flag = 0;
while (low <= hight)
{
mid = (low + hight) / 2;
if (x1 < a[mid]) // 插入应在左区间
hight = mid - 1;
else if(x1 > a[mid])
low = mid + 1; // 插入应在右区间
else
{
flag = mid;
break;
}
}
return flag;
}
void HalfFind::show()
{
int i;
for(i=0; i<15; i++)
{
cout << array[i] << " ";
}
}
void main()
{
int i;
int ob[15] = {1,3,5,8,7,4,2,6,10,11,12,13,9,15,14};
HalfFind obj(ob, 15);
cout << "输出的数组是:" << endl;
obj.show();
cout << endl;
cout << "由小到大排序:" << endl;
obj.arraySort(ob, 15);
obj.show();
cout << endl;
i = obj.halfFind(ob, 13, 15);
if (i == 0)
cout << "找不到";
else
cout << "所要找的元素的位置:" << i << endl;
}