1. 程式人生 > >經典的氣泡排序法 JAVA實現

經典的氣泡排序法 JAVA實現

public

class BubbleSort { /** *@paramargs *@authorwu,yaowen*@paramargs */ //initialize the array by Math.random() publicint[] initArray(int arrLen){ int len = arrLen; int a[] = newint[len]; for(int i=0; i<len; i++){

a[i] = (

int)(Math.random()*100);

}

return a;

}

// End of initArray() //print the array public
void printArray(int a[]){ for (int i = 0; i < a.length; i++) {

System.

out.print(a[i] + " ");

}

}

// End of printArray //taxis the array publicvoid bubbleSort(int arr[]) { for (int i = 0; i < arr.length; i++) { // for 1round j, chose the biggest number; for (int j = 0; j < arr.length - i - 1; j++) {
if (arr[j + 1] < arr[j]) { int t = arr[j + 1];

arr[j + 1] = arr[j];

arr[j] = t;

}

}

// End of 2nd For

}

}

// End of bubbleSort() publicstaticvoid main(String[] args) { // TODO Auto-generated method stub finalint ARRAY_SIZE = 10; int a[] = newint[ARRAY_SIZE];

BubbleSort b =

new BubbleSort();

a = b.initArray(ARRAY_SIZE);

/**

for(inti=0;i<ARRAY_SIZE; i++){ a[i]=(int)(Math.random()*100); }

*/

//print the original array

System.

out.println("The original order of the array is: ");

b.printArray(a);

/**

for(inti=0;i< a.length; i++) { System.out.print(a[i]+""); }

*/

b.bubbleSort(a);

System.

out.println("/n/nAfter sorted, the order of the array is: ");

b.printArray(a);

/**

for(inti=0;i< a.length; i++) { System.out.print(a[i]+""); }

*/

} // End of main()

}

out put(by random):

The original order of the array is:

65 92 21 15 33 98 64 9 20 50

After sorted, the order of the array is:

9 15 20 21 33 50 64 65 92 98