隨便大小10個數【序號1-10】,按從小到大輸出【同時輸出相應序號】
import java.util.Arrays;
import java.util.Random;
public class TestSort{
public static void main(String[] args) {
sort1();
System.out.println("\n");
sort2();
}
public static void sort1(){
int[][]ary = new int[10][2];//二維陣列
Random r = new Random();
for (int i = 0; i < 10; i++) {
ary[i][0]=i+1;//存放序號
ary[i][1]=r.nextInt(100);//存放數值
}
for (int i = 0; i < ary.length; i++) {
System.out.print("["+ary[i][0]+"]");
System.out.print(",");
System.out.print(ary[i][1]+" ");
}
System.out.println();
//氣泡排序
for (int i = 0; i < ary.length-1; i++) {
for (int j = 0; j < ary.length-i-1; j++) {
if(ary[j][1]>ary[j+1][1]){
int temp1 = ary[j][0];
int temp2=ary[j][1];
ary[j][0]=ary[j+1][0];
ary[j][1]=ary[j+1][1];
ary[j+1][0]=temp1;
ary[j+1][1]=temp2;
}
}
}
for (int i = 0; i < ary.length; i++) {
System.out.print("["+ary[i][0]+"]");
System.out.print(",");
System.out.print(ary[i][1]+" ");
}
}
public static void sort2(){
int[]ary = new int[10];
Random r = new Random();
for (int i = 0; i < ary.length; i++) {
ary[i]=r.nextInt(100);
}
System.out.println(Arrays.toString(ary));
boolean[]used = new boolean[10];//用來記錄那些數已經輸出過了
for (int i = 0; i < ary.length; i++) {
int minIndex = 0;//最小數下標
while(used[minIndex]){
minIndex++;//忽略已經輸出過的
}
for (int j = minIndex+1; j < ary.length; j++) {
if(used[j]){
continue;//忽略已經輸出過的
}
if(ary[j]<ary[minIndex]){
minIndex=j;
}
}
System.out.print("["+(minIndex+1)+"],"+ary[minIndex]+" ");//輸出這個最小的數以及它的序號
used[minIndex]=true;
}
}
}