Java--数组运算和排列

来源:互联网 发布:ui网络授课能学会吗 编辑:程序博客网 时间:2024/06/08 07:24
package com.lovo;public class Test02 {public static void main(String[] args) {int[] a = new int[5];System.out.print("排序前: ");for(int i = 0; i < a.length; i++) {a[i] = (int) (Math.random() * 99 + 1);System.out.print(a[i] + "  ");}// 简单选择排序for(int i = 0; i < a.length - 1; i++) {int minIndex = i;for(int j = i + 1; j < a.length; j++) {if(a[j] < a[minIndex]) {minIndex = j;}}if(minIndex != i) {int temp = a[i];a[i] = a[minIndex];a[minIndex] = temp;}}System.out.print("\n排序后: ");for(int x : a) {System.out.print(x + "  ");}}}
package  com.lovo;public class Test03 {public static void main(String[] args) {int[] a = new int[5];System.out.print("排序前: ");for(int i = 0; i < a.length; i++) {a[i] = (int) (Math.random() * 99 + 1);System.out.print(a[i] + "  ");}// 冒泡排序boolean swapped = true;// 有没有发生过交换for(int i = 1; swapped && i <= a.length - 1; i++) {swapped = false;// 表示尚未发生交换for(int j = 0; j < a.length - i; j++) {if(a[j] > a[j + 1]) {int temp = a[j];a[j] = a[j + 1];a[j + 1] = temp;swapped = true;}}}System.out.print("\n排序后: ");for(int x : a) {System.out.print(x + "  ");}}}


0 0
原创粉丝点击