/**
*
* 冒泡排序
*
*
*/
public class ArrayTest1 {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
int[] arr = { 5, 1, 4, 2, 7 };
// 排序前
printArray(arr);
// 排序后
bubbleSort(arr);
printArray(arr);
}
/**
* 冒泡排序
* @param arr
*/
public static void bubbleSort(int []arr){
for(int x=0;x<arr.length;x++){
for(int y=0;y<arr.length-x-1;y++){//-x:让每次比较的元素减少,-1:避免数组越界
if(arr[y]>arr[y+1]){
int temp=arr[y];
arr[y]=arr[y+1];
arr[y+1]=temp;
}
}
}
}
/**
* 打印数组
*/
public static void printArray(int[] arr) {
System.out.print("[");
for (int x = 0; x < arr.length; x++) {
if (x != arr.length - 1) {
System.out.print(arr[x] + ", ");
} else {
System.out.println(arr[x] + "]");
}
}
}
}