键盘录入数组,对数组进行冒泡排序后,进行遍历输出结果
import java.util.Scanner;
public class ArraybubbleDemo {
public static void main(String[] args) {
//创建键盘录入
Scanner sc = new Scanner(System.in);
System.out.println("请输入数组的长度:");
int len = sc.nextInt();
int arr[] = new int[len];
System.out.println("请输入数组元素 : ");
for(int i =0; i < arr.length ; i++){
arr[i] = sc.nextInt();
}
//排序
System.out.println("功能排序后:");
bubbleSort(arr);
//输出结果:遍历功能
printArray(arr);
}
//遍历功能
public static void printArray(int[] arr) {
System.out.print("[");
for (int x=0;x<arr.length;x++) {
if(x == arr.length-1) {
System.out.println(arr[x]+"]");
}else {
System.out.print(arr[x]+",");
}
}
}
public static void bubbleSort(int [] arr) {
for(int x = 0;x< arr.length-1;x++) {
for(int y = 0;y<arr.length-1-x;y++) {
if(arr[y]>arr[y+1]) {
int temp = arr[y];
arr[y] = arr[y+1];
arr[y+1]=temp;
}
}
}
}
}
程序运行结果如下: