java中数组的重要基础代码
一、数组的概念
数组是同一种类型数据的集合;即能够存放多个相同类型的数据的容器。
二、数组的基本语法格式
- 数组类型[ ] 数组名 = new 数组类型[数组长度] ;
- 数组类型[ ] 数组名 = new 数组类型[ ] {数组元素0,数组元素1,…};
- 数组类型[ ] 数组名 = {数组元素0,数组元素1,…}
三、数组的内存分配
int nums[] = new int[3];
四、数组的常用操作算法
1.数组遍历
public class Demo {
public static void main(String[] args) {
int nums[] = {7,45,30,35,13,11,457,789,12,345,23,87,34,90,18,20,32,45};
for (int i = 0;i<nums.length;i++){//数组过长,使用数组.length表示数组长度
System.out.println(nums[i]);
}// Arrays.toString 快速打印数组内容 会打印 []
System.out.println(Arrays.toString(nums));
}
}
2.数组求和
public class Demo {
public static void main(String[] args) {
int nums[] ={7,45,30,35,13,11,457,789,12,345,23,87,34,90,18,20,32,45};
int sum = 0;//定义sum为求和值
int length = nums.length;//定义length为数组的长度
for (int i = 0; i < length; i++) {
sum += nums[i];
}
System.out.println("数组和为"+sum);
}
}
3.数组求最值
public class Demo {
public static void main(String[] args) {
int nums[] = {7,45,30,35,13,11,457,789,12,345,23,87,34,90,18,20,32,45};
int max = nums[0];//由第一位作为最大值开始一一比较
for (int i = 1;i<nums.length;i++){
if (max<nums[i]){
max = nums[i];//如果比最大值大就替换,反之进入循环继续比较
}
}
System.out.println("该数组最大值为"+max);
}
}
4.反转数组
public class Demo {
public static void main(String[] args) {
int nums[] = {7,45,30,35,13,11,457,789,12,345,23,87,34,90,18,20,32,45};
for(int start=0,end=nums.length-1;start<end;start++,end--){
//start为数组第一位元素角标,end为最后一位元素的角标。
int temp = nums[start];
nums[start] = nums[end];
nums[end] = temp;
//使用三元置换将第一位与最末位进行置换,在循环中依次进行置换,直到start等于end,停止循环
}
for(int i = 0;i<nums.length;i++){
if(i != nums.length-1){
System.out.print(nums[i]+",");
}else//输出反转后的数组
System.out.println(nums[i]);
}
}
}
5.数组选择排序
import java.util.Arrays;
public class Demo {
public static void main(String[] args) {
int nums[] = {23, 30, 35, 7, 11};
for (int x = 0; x < nums.length - 1; x++) //x为比较的元素角标
for (int y = x + 1; y < nums.length; y++) //内层循环为x之后的各位元素
{
if (nums[x] > nums[y]) //当第x位大于第y位,位置互换,依次进行
{int temp = nums[x];
nums[x] = nums[y];
nums[y] = temp;
}
}
}
System.out.println(Arrays.toString(nums));//打印数组
}
}
6.数组冒泡排序
import java.util.Arrays;
public class Demo {
public static void main(String[] args) {
int nums[] = {23, 30, 35, 7, 11};
for (int i = 0; i < nums.length - 1; i++) //外层循环表示从第一位开始比较
{
for (int j = 0;j<nums.length-1-i;j++){//内存循环表示之后依次比较
if (nums[j]>nums[j+1]){//较大数后置
int temp = nums[j];
nums[j] = nums[j+1];
nums[j+1] = temp;
}
}
}
System.out.println(Arrays.toString(nums));
}
}
7.数组折半查找(二分法)
public class Demo {
public static void main(String[] args) {
int nums[] = {7,11,13,15,21,23,24,30,31,32,34};//数组为升序排列
int k = 30,min = 0,max = nums.length-1,mid = (min+max)/2;
while (k !=nums[mid]){
if (k>nums[mid]){
min = mid+1;
}
if (k<nums[mid]){
max = mid-1;
}
mid = (max + min)/2;
if (max<min){
mid = -1;
break;
}
}
System.out.println("该数为数组的第"+mid+"个数");
}
}