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

}


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

全部评论

相关推荐

不愿透露姓名的神秘牛友
11-26 18:54
说等下个版本吧的发呆爱好者很贪睡:佬最后去了哪家呀
点赞 评论 收藏
分享
11-07 13:31
怀化学院 Java
勇敢牛牛不怕难:又疯一个
点赞 评论 收藏
分享
totoroyyw:千年老妖😂
投递华为等公司10个岗位
点赞 评论 收藏
分享
评论
点赞
收藏
分享
牛客网
牛客企业服务