PAT基础编程题目-6-13 折半查找
PAT基础编程题目-6-13 折半查找
题目详情
C语言版
#include<stdio.h>
#define MAXSIZE 50
typedef int KeyType;
typedef struct
{
KeyType key;
} ElemType;
typedef struct
{
ElemType* R;
int length;
} SSTable;
void Create(SSTable& T)
{
int i;
T.R = new ElemType[MAXSIZE + 1];
scanf_s("%d",&T.length);
for (i = 1; i <= T.length; i++)
scanf_s("%d",&T.R[i].key);
}
int Search_Bin(SSTable T, KeyType k);
int main()
{
SSTable T; KeyType k;
Create(T);
scanf_s("%d",&k);
int pos = Search_Bin(T, k);
if (pos == 0) printf("NOT FOUND\n");
else printf("%d\n", pos);
return 0;
}
int Search_Bin(SSTable T, KeyType k) {
int low = 1;
int high = T.length;
int mid;
while (low <= high) {
mid = (low + high) / 2;
if (T.R[mid].key == k)
return mid;
else if (T.R[mid].key > k)
high = mid - 1;
else
low = mid + 1;
}
return 0;
}
C++版
#include<iostream>
using namespace std;
#define MAXSIZE 50
typedef int KeyType;
typedef struct
{
KeyType key;
} ElemType;
typedef struct
{
ElemType* R;
int length;
} SSTable;
void Create(SSTable& T)
{
int i;
T.R = new ElemType[MAXSIZE + 1];
cin >> T.length;
for (i = 1; i <= T.length; i++)
cin >> T.R[i].key;
}
int Search_Bin(SSTable T, KeyType k);
int main()
{
SSTable T; KeyType k;
Create(T);
cin >> k;
int pos = Search_Bin(T, k);
if (pos == 0) cout << "NOT FOUND" << endl;
else cout << pos << endl;
return 0;
}
int Search_Bin(SSTable T, KeyType k) {
int low = 1;
int high = T.length;
int mid;
while (low<=high) {
mid = (low + high) / 2;
if (T.R[mid].key == k)
return mid;
else if (T.R[mid].key > k)
high = mid - 1;
else
low = mid + 1;
}
return 0;
}
Java版
public class Main{
private static final int MAXN = 50;
public static void main(String[] args) {
int length=0,k=0;
int [] T = new int[MAXN];
Scanner scanner = new Scanner(System.in);
if(scanner.hasNext()) {
length = scanner.nextInt();
for (int i = 1; i <= length; i++) {
T[i] = scanner.nextInt();
}
k = scanner.nextInt();
}
scanner.close();
int binarySearch = Arrays.binarySearch(T, 1, length+1, k);
if(binarySearch>0)
System.out.println(binarySearch);
else
System.out.println("NOT FOUND");
}
}
创作不易,喜欢的话加个关注点个赞,谢谢谢谢谢谢!