解法不一定是最有效率、最低複雜度、最佳效能的,完全是依照自己的想法做!
---
泡沫排序法:給定一數列後,進行排序時會從第一位開始,與第二位進行比較,若數字較大則往前移動兩者互換位置;再用第二位與第三位比較、第三位與第四位比較...。所以當進行第一次後,最大的數已被排在最後面,理論上需要將n個數字都跑一遍,但這邊可使用一個布林變數進行判斷,若有一次沒有進行任何換位的動作代表數列已經是排序完成,後面不需再執行。
假設題目要求:給一任意數N,生成長度為N的整數數列,並以此進行bubble sort。
程式碼可如下:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package algorithms; | |
import java.util.Scanner; | |
public class Sorting { | |
static int numSize = 0; | |
static int[] aryRandomNumbers; | |
static int[] afterSorting; | |
public static void main(String[] args) { | |
// TODO Auto-generated method stub | |
Scanner scanner = new Scanner(System.in); | |
System.out.println("input a number, it will generating n-size random rumber"); | |
numSize = scanner.nextInt(); | |
//產生長度為n的隨機整數數列 | |
getRandomNumbers(numSize); | |
bubbleSort(); | |
} | |
private static void bubbleSort() { | |
SortLoop: | |
//將所有數字跑一次, 直到被離開迴圈 | |
for(int j = 0; j < aryRandomNumbers.length - 1; j++) { | |
boolean isSwap = false; //if no change, means the array is sorted done | |
//從第0位開始往上比 | |
for(int i = 0; i < aryRandomNumbers.length - 1; i++) { | |
if(aryRandomNumbers[i] > aryRandomNumbers[i+1]) { | |
int temp = aryRandomNumbers[i+1]; | |
aryRandomNumbers[i+1] = aryRandomNumbers[i]; | |
aryRandomNumbers[i] = temp; | |
isSwap = true; | |
} | |
} | |
if(!isSwap) break SortLoop; | |
} | |
printCurrentArray(); | |
} | |
private static void getRandomNumbers(int size) { | |
aryRandomNumbers = new int[size]; | |
for(int i = 0; i < numSize; i++) { | |
int num = (int)(Math.random()*15 + 1); | |
aryRandomNumbers[i] = num; | |
} | |
printCurrentArray(); | |
} | |
private static void printCurrentArray() { | |
// TODO Auto-generated method stub | |
for(int element:aryRandomNumbers ) { | |
System.out.print(element + " "); | |
} | |
System.out.println(""); | |
} | |
} |