You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
Java/Java入门 - 数组进阶.txt

141 lines
3.4 KiB

1.数组的复制
package step1;
import java.util.Scanner;
public class HelloWorld {
public static void main(String[] args) {
//动态构建arr1
int[] arr1 = new int[3];
Scanner sc = new Scanner(System.in);
for(int i = 0 ; i< arr1.length ; i++){
arr1[i] = sc.nextInt();
}
/********** Begin **********/
//创建数组arr2
int[] arr2 = new int[arr1.length];
//使用for循环将arr1的数据复制给arr2
for (int j = 0; j < arr1.length; j++) {
arr2[j] = arr1[j];
}
//输出arr2
for (int array : arr2)
System.out.println(array);
/********** End **********/
}
}
2.数组中元素的查找
package step2;
import java.util.Scanner;
public class HelloWorld {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
//str为要查找的字符串
String str = sc.next();
/********** Begin **********/
//创建数组 arr 给数组赋值 {"张三","张三丰","张无忌","王二麻子","张富贵"}
String[] arr = {"张三", "张三丰", "张无忌", "王二麻子", "张富贵"};
for (int i = 0; i < arr.length; i++) {
int j = i + 1;
if (str.equals(arr[i]))
System.out.println(str + "在数组的第" + j + "个位置");
}
/********** End **********/
}
}
3.交换算法
package step3;
import java.util.Scanner;
public class HelloWorld {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int a = sc.nextInt();
int b = sc.nextInt();
/********** Begin **********/
//将a的值赋给b b的值赋给a
int temp=a;
a=b;
b=temp;
/********** End **********/
System.out.println(a);
System.out.println(b);
}
}
4.选择排序
package step4;
import java.util.Arrays;
import java.util.Scanner;
public class HelloWorld {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
//动态创建数组
int[] arr = new int[sc.nextInt()];
for(int i = 0 ; i< arr.length ; i++){
arr[i] = sc.nextInt();
}
/********** Begin **********/
for (int i = 0; i < arr.length - 1; i++) {
int k = i;
for (int j = k + 1; j < arr.length; j++) {
if (arr[j] > arr[k]) {
k = j;
}
}
if (i != k) {
int temp = arr[i];
arr[i] = arr[k];
arr[k] = temp;
}
}
System.out.println(Arrays.toString(arr));
/********** End **********/
}
}
5.冒泡排序
package step5;
import java.util.Arrays;
import java.util.Scanner;
public class HelloWorld {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
//动态创建数组
int[] arr = new int[sc.nextInt()];
for(int i = 0 ; i< arr.length ; i++){
arr[i] = sc.nextInt();
}
/********** Begin **********/
for (int i = 0; i < arr.length - 1; i++) {
for (int j = 0; j < arr.length - i - 1; j++) {
if (arr[j] > arr[j + 1]) {
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
System.out.println(Arrays.toString(arr));
/********** End **********/
}
}