冒泡排序(Bubble Sort)是一種簡單的排序算法。它重復地走訪過要排序的數列,一次比較兩個元素,如果他們的順序錯誤就把他們交換過來。走訪數列的工作是重復地進行直到沒有再需要交換,也就是說該數列已經排序完成。這個算法的名字由來是因為越小的元素會經由交換慢慢“浮”到數列的頂端。
冒泡排序算法的運作如下:
- 比較相鄰的元素。如果第一個比第二個大,就交換他們兩個。
- 對每一對相鄰元素作同樣的工作,從開始第一對到結尾的最后一對。在這一點,最后的元素應該會是最大的數。
- 針對所有的元素重復以上的步驟,除了最后一個。
- 持續每次對越來越少的元素重復上面的步驟,直到沒有任何一對數字需要比較。
冒泡排序的過程圖:

代碼:
1 public class BubbleSort{
2 public static void main(String[] args){
3 int score[] = {67, 69, 75, 87, 89, 90, 99, 100};
4 for (int i = 0; i < score.length -1; i++){ //最多做n-1趟排序
5 for(int j = 0 ;j < score.length - i - 1; j++){ //對當前無序區間score[0......length-i-1]進行排序(j的范圍很關鍵,這個范圍是在逐步縮小的)
6 if(score[j] < score[j + 1]){ //把小的值交換到后面
7 int temp = score[j];
8 score[j] = score[j + 1];
9 score[j + 1] = temp;
10 }
11 }
12 System.out.print("第" + (i + 1) + "次排序結果:");
13 for(int a = 0; a < score.length; a++){
14 System.out.print(score[a] + "\t");
15 }
16 System.out.println("");
17 }
18 System.out.print("最終排序結果:");
19 for(int a = 0; a < score.length; a++){
20 System.out.print(score[a] + "\t");
21 }
22 }
23 }
Java中的快速排序源代碼
public class QuickSort {
public static void main(String[] args) {
Random random=new Random();
int[] pData=new int[10];
for(int i=0;i<pData.length;i++){ //隨機生成10個排序數
Integer a =random.nextInt(100);
pData[i]= a;
System.out.print(pData[i]+" ");
}
System.out.println();
int left=0;
int right=pData.length-1;
Sort(pData,left,right);
for(int i=0;i<pData.length;i++){
System.out.print(pData[i]+" ");
}
System.out.println();
}
public static int[] Sort(int[] pData, int left, int right){
int middle,strTemp;
int i = left;
int j = right;
middle = pData[(left+right)/2];
do{
while((pData[i]<middle) && (i<right))
i++;
while((pData[j]>middle) && (j>left))
j--;
if(i<=j){
strTemp = pData[i];
pData[i] = pData[j];
pData[j] = strTemp;
i++;
j--;
}
for(int k=0;k<pData.length;k++){
System.out.print(pData[k]+" ");
}
System.out.println();
}while(i<j);//如果兩邊掃描的下標交錯,完成一次排序
if(left<j)
Sort(pData,left,j); //遞歸調用
if(right>i)
Sort(pData,i,right); //遞歸調用
return pData;
}
}
二分法就是在排序數組中從前到后逐漸的進行排序,是循環一次后前面的數據就是有序的,然后就以此往后使得整個數組為有序的數組。(二分法排序示例代碼:)
package binarySort;
public class binarySort {
public static void binary_sort(int a[])
{
int i,j,temp;
int low ,hight ,mid;
for(i=1;i<a.length;i++)
{
temp = a[i];
low = 0;
hight = i-1;
while(low<=hight)
{
mid = (low+hight)/2;
if(a[mid]>temp)
hight =mid -1;
else
low = mid + 1;
}
for(j =i-1;j>hight;j--)
a[j+1] = a[j];
a[hight+1] = temp;
}
}
public static void main(String[] args) {
int a[] = {2,6,9,8,4,7,3,1,0,5};
binary_sort(a);
for(int i=0;i<a.length;i++)
System.out.print(a[i]+ " ");
}
}