当前位置:网站首页>一维数组的应用
一维数组的应用
2022-07-27 02:19:00 【黑白不纯】
1.求一组数的最大值
思路:从这组数中选取一个值,然后让它依次和其他的数进行大小比较.
public class Demo1 {
public static void main(String[] args) {
int[] sums = new int[]{1,5,777,43,5,577,666,778};
int max = sums[0];
for (int i = 0; i < sums.length; i++) {
if(max<sums[i]){
max=sums[i];
}
}
System.out.println(max);
}
}
2.在一组数中插入一个数
思路:先定义一个新数组,将原数组的值对应赋给新数组.然后确定插入的位置,从后往前,依次将前一个数的值赋给后一个数.
import java.util.Scanner;
public class Demo2 {
public static void main(String[] args) {
int[] a ={90,87,65,43,21};
int[] b =new int[a.length+1];
for (int i = 0; i <b.length-1 ; i++) {
b[i]=a[i];
}
System.out.println("插入一个数");
Scanner sc = new Scanner(System.in);
int c = sc.nextInt();
int index=b.length-1;
for (int i = 0; i <b.length; i++) {
if(c>b[i]){
index=i;
break;
}
}
for (int i = b.length-1; i>index ; i--) {
b[i]=b[i-1];
}
b[index]=c;
for (int i = 0; i < b.length; i++) {
System.out.println(b[i]);
}
}
} 
3.冒泡排序-----数字升序排序
思路:两两相比小靠前,找到比较轮数与比较次数的关系.
//使用冒泡排序对输入的5名学员成绩进行升序排列
import java.util.Scanner;
public class Demo6 {
public static void main(String[] args) {
int[] student=new int[5];
Scanner sc = new Scanner(System.in);
System.out.println("请输入5名学生成绩");
for (int i = 0; i < student.length; i++) {
student[i]=sc.nextInt();
}
for (int i = 0; i < student.length-1; i++) {
for (int j =0 ; j <student.length-1-i ; j++) {
if(student[j]>student[j+1]){
int index=student[j];
student[j]=student[j+1];
student[j+1]=index;
}
}
}
for (int k = 0; k < student.length; k++) {
System.out.println(student[k]);
}
}
}

边栏推荐
猜你喜欢

【树链剖分】模板题

Introduction to database - Introduction to database

MySQL underlying data structure

若依框架代码生成详解
![Machine learning [Matplotlib]](/img/d1/31ec2f96ca96465c6863798c7db179.jpg)
Machine learning [Matplotlib]

Connman introduction

Explain tool actual operation

Worthington papain dissociation system solution

flask_ Reqparse parser inheritance in restful

复盘:图像有哪些基本属性?关于图像的知识你知道哪些?图像的参数有哪些
随机推荐
Characteristics and determination scheme of Worthington pectinase
Reading notes of Kazuo Inamori's advice to young people
Tool class of localdatetime sorted out by yourself
Spark Learning Notes (V) -- spark core core programming RDD conversion operator
Principle understanding and application of hash table and consistent hash
在typora中插入图片和视频
Explain
Ring counting (Northern Polytechnic machine test questions) (day 83)
飞腾腾锐 D2000 荣获数字中国“十大硬核科技”奖
复盘:DFS与BFS的主要区别,在思想上的区别,代码实现上的区别
[common search questions] 111
"Date: write error: no space left on device" solution
Add support for @data add-on in idea
Application, addition and deletion of B-tree
Textbox in easyUI inserts content at the cursor position
榕树贷款C语言结构体里的成员数组和指针
Redis source code learning (33), command execution process
Duplicate disc: what are the basic attributes of an image? What do you know about images? What are the parameters of the image
Worthington papain dissociation system solution
DTS搭载全新自研内核,突破两地三中心架构的关键技术|腾讯云数据库