Java学习笔记之数组

1、一维数组

        一维数组定义方法

        格式一:数据类型[] 数组名称 = new 数据类型[数组长度];

        格式二:数据类型[] 数组名称 = {内容1,内容2,内容3.,...,内容n };

        格式三:数据类型[] 数组名称= new 数据类型[]{内容 1,内容 2,内容 3...内容 n};

        格式四:数据类型[] 数组名称;

                        格式四属于只创建了数组引用名, 并未在内存创建数组空间。

        数组下标

        数组中内容的数字序号,从 0 开始 ,对于长度为 n 的数组,下标从0到n-1。

int[] arr = {11,22,33,44,55};
//arr[0]的内容为11,是数组中的第1个数字
//arr[4]的内容为55,是数组中的第5个数字
System.out.println(arr[0]);//可以打印出来观察
System.out.println(arr[4]);

        数组长度获取

        数组名称.length
System.out.print(arr.length);

        数组的遍历

//数组的遍历
for(int index=0;index<ages.length;index++) {
	//index: 0 1 2 3 4 
	System.out.println(ages[index]);
}

2、冒泡排序

升序排列的口诀:降序排序的口诀:
N个数字来排队
两两相比小靠前,
外层 循环length-1
内层循环length-i-1
N个数字来排队
两两相比大靠前,
外层 循环length-1        
内层循环length-i-1
int[] nums = {20,15,18,13,30,60};
int temp;
//外层循环控制的是, 比较的轮数。
//外层循环次数: length-1
for(int i=0;i<nums.length-1;i++) {
	//内层循环控制的是,每轮比较的次数
	//第i轮(i从0开始计算), 比较次数为:length-i-1
	for(int j=0;j<nums.length-i-1;j++) {
		if(nums[j]>nums[j+1]) {
			//两两相比, 满足移动条件
			temp = nums[j];
			nums[j] = nums[j+1];
			nums[j+1] = temp;
		}
	}
}

3、二分查找

        二分查找要求数组数据必须采用 顺序存储 结构有序排列。
public class Demo5 {

	/**
	 * 二分查找(折半查找)
	 */
	public static void main(String[] args) {
		int[] nums = {10,20,30,40,50,60,70,80,90};
		
		//要查找的数据
		int num = 20;
		
		//关键的三个变量:
		//1.	最小范围下标
		int minIndex = 0;
		//2.	最大范围下标
		int maxIndex = nums.length-1;
		//3.	中间数据下标
		int centerIndex = (minIndex+maxIndex)/2;
		while(true) {
			System.out.println("循环了一次");
			if(nums[centerIndex]>num) {
				//中间数据较大
				maxIndex = centerIndex-1;
			}else if(nums[centerIndex]<num) {
				//中间数据较小
				minIndex = centerIndex+1;
			}else {
				//找到了数据  数据位置:centerIndex
				break;
			}
			
			if(minIndex > maxIndex) {
				centerIndex = -1;
				break;
			}
			//当边界发生变化, 需要更新中间下标
			centerIndex = (minIndex+maxIndex)/2;
		}
		
		System.out.println("位置:"+centerIndex);
		
	}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值