Linux教程網
下面是Java冒泡排序法的示例代碼
- package com.jadyer.sort;
-
- /**
- * 冒泡排序法
- * @see JDK本身也提供了數組排序API,不妨參考一下,即Arrays.sort(array)
- */
- public class BubbleSort {
- public static void main(String[] args) {
- bubbleSort(new int[]{4,6,9,8,3,2});
- }
-
- public static void bubbleSort(int[] array){
- for(int i=0; i<array.length-1; i++){
- for(int j=0; j<array.length-i-1; j++){
- if(array[j] > array[j+1]){
- int temp = array[j];
- array[j] = array[j+1];
- array[j+1] = temp;
- }
- }
- System.out.print("這是第" + (i+1) + "次排序,排序結果為: ");
- for(int k=0; k<array.length; k++){
- System.out.print(array[k] + " ");
- }
- System.out.println();
- }
- }
- }
Copyright ©
Linux教程網 All Rights Reserved