package demo;
public class MaoPao {
public static void main(String[] args) {
//定义一个数组
int [] arr = {1,6,3,9,4,2,5,8,0,7};
System.out.println("排序前:" + arrayToString(arr));
/*
//第一次比较
for (int i = 0; i < arr.length - 1 - 0; i++) {
if (arr [i] > arr [i + 1]){
int temp = arr [i];
arr [i] = arr [i + 1];
arr [i + 1] = temp;
}
}
System.out.println("第一次比较后:" + arrayToString(arr));
//第二次比较
for (int i = 0; i < arr.length - 1 - 1; i++) {
if (arr [i] > arr [i + 1]){
int temp = arr [i];
arr [i] = arr [i + 1];
arr [i + 1] = temp;
}
}
System.out.println("第二次比较后:" + arrayToString(arr));
//第三次比较
for (int i = 0; i < arr.length - 1 - 2; i++) {
if (arr [i] > arr [i + 1]){
int temp = arr [i];
arr [i] = arr [i + 1];
arr [i + 1] = temp;
}
}
System.out.println("第三次比较后:" + arrayToString(arr));
//第四次比较
for (int i = 0; i < arr.length - 1 - 3; i++) {
if (arr [i] > arr [i + 1]){
int temp = arr [i];
arr [i] = arr [i + 1];
arr [i + 1] = temp;
}
}
System.out.println("第四次比较后:" + arrayToString(arr));
*/
for (int x = 0;x < arr.length - 1;x ++){
for (int i = 0; i < arr.length - 1 - x; i++) {
if (arr [i] > arr [i + 1]){
int temp = arr [i];
arr [i] = arr [i + 1];
arr [i + 1] = temp;
}
}
}
System.out.println("排序后:" + arrayToString(arr));
}
public static String arrayToString(int [] arr){
StringBuilder s = new StringBuilder();
s.append("[");
for (int i = 0; i < arr.length; i++) {
if (i == arr.length - 1){
s.append(arr [i]);
}else {
s.append(arr [i]).append(", ");
}
}
s.append("]");
String str = s.toString();
return str;
}
}