PAT基础编程题目-6-13 折半查找

PAT基础编程题目-6-13 折半查找

题目详情

题目地址:https://pintia.cn/problem-sets/14/problems/44932

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");
	}

}


创作不易,喜欢的话加个关注点个赞,谢谢谢谢谢谢!

全部评论

相关推荐

10-14 10:56
已编辑
长沙学院 嵌入式软件开发
痴心的00后拿到了ssp:hr面挂了,无所谓了反正不去😃
点赞 评论 收藏
分享
dongsheng66:如果想进大厂的话,在校经历没必要占这么大篇幅,可以把专业技能单独放一个专栏写,可以加个项目经历
点赞 评论 收藏
分享
点赞 收藏 评论
分享
牛客网
牛客企业服务