java的简单程序

本文介绍了一个Java程序,该程序使用选择法排序算法对数组进行排序,并通过二分查找法判断用户输入的整数是否存在于已排序的数组中。程序包含Sort1类用于排序,Search类用于查找。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

程序的执行入口:

import java.util.*;
public class Sort {
	public static void main(String[] args ){
		int[] a={12,45,67,89,123,-45,67};
		int N=a.length;
		Scanner scanner =new Scanner(System.in);
		System.out.println("请输入一个整数判断是否在相应的数组中:");
		int number=scanner.nextInt();
		Sort1 b=new Sort1();
		b.sort(N,a);
		Search d=new Search();
		int count=d.search(number,N,a);

	if(count>N/2)
		System.out.printf("%d不在数组中",number);
	else
		System.out.printf("%d不在数组中",number);
	}
}

程序的search部分:

public class Search {
	int search(int number,int N,int[] a){
		int count=0;
		int start=0,end,middle;
		end=N;
		middle=(start+end)/2;
		while(number!=a[middle]){
			if(number>a[middle])
				start=middle;
			else if(number<a[middle])
				end=middle;
			middle=(start+end)/2;
			count++;
			if(count>N/2)
				break;
		}
	return count;
}
}


选择法排序:

public class Sort1 {				//选择法排序
	void sort(int N,int[] a){
		for(int i=0;i<N;i++){
			for(int j=i+1;j<N;j++){
				if(a[j]<a[i]){
					int t=a[j];
					a[j]=a[i];
					a[i]=t;
				}
			}
		}
	}

}


 判断一个数是否在相应的数组中:

import java.util.*;
public class Sort {
	public static void main(String[] args ){
		int[] a={12,45,67,89,123,-45,67};
		int N=a.length;
		Scanner scanner =new Scanner(System.in);
		System.out.println("请输入一个整数判断是否在相应的数组中:");
		int number=scanner.nextInt();
		Sort1 b=new Sort1();
		b.sort(N,a);
		Search d=new Search();
		int count=d.search(number,N,a);

	if(count>N/2)
		System.out.printf("%d不在数组中",number);
	else
		System.out.printf("%d不在数组中",number);
	}
}



心得体会:

java程序只有一个程序执行入口,从建立对象到执行调用对象,时时刻刻都是对象。从开始就要养成建立工程的感觉,慢慢来,就会接近实际的项目!

坚持就是胜利@!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值