最近剛看算法導論,想自己比較一下冒泡排序跟歸并排序。
歸并排序的算法複雜度:nlogn
冒泡排序的算法複雜度:n^2
第一次發部落格,各位大蝦有什麼建議盡管提,非常感謝!
public class Sort {
/**
* @param
* @author darkhorse_pxf
*/
static int count=1; //用于計算歸并排序操作次數
static int count2=1; 用于計算冒泡排序操作次數
public static void main(String[] args) {
int a[]={54,47,15,475,21,57,67,18,88,245};
int b[]={54,47,15,475,21,57,67,18,88,245};
System.out.println("歸并排序:");
mergeSort(a,0,a.length-1); //歸并排序
System.out.println("歸并排序共執行"+count+"次");
System.out.println("冒泡排序:");
bubbleSort(b); //冒泡排序
System.out.println("冒泡排序共執行"+count2+"次");
/**測試Merge
int a[]={1,3,5,7,9,2,4,6,8,10};
Merge.Merge(a, 0, 4, a.length-1);
for(int i=0;i<a.length;i++){
System.out.print(a[i]+" ");
}
System.out.println();
*/
}
private static void bubbleSort(int[] b) { //冒泡排序
int k;
for(int i=0;i<b.length;i++){
for(int j=i;j<b.length;j++){
if(b[i]<=b[j]){
k=b[i];
b[i]=b[j];
b[j]=k;
count2++;
}
}
for(int x=0;x<b.length;x++){
System.out.print(b[x]+" ");
}
System.out.println();
}
}
public static void mergeSort(int[] numbers,int firstNumber,int lastNumber) {
if(firstNumber<lastNumber){
int midleNumber=(firstNumber+lastNumber)/2;
mergeSort(numbers,firstNumber,midleNumber);
mergeSort(numbers,midleNumber+1,lastNumber);
Merge(numbers, firstNumber, midleNumber, lastNumber);
for(int i=0;i<numbers.length;i++){
System.out.print(numbers[i]+" ");
}
System.out.println();
}
}
public static void Merge(int numbers[],int p,int q,int r){
int n1=q-p+1;
int n2=r-q;
int Left[]=new int[n1];
int Right[]=new int[n2];
for(int i=0;i<Left.length;i++){
Left[i]=numbers[i+p];
}
for(int j=0;j<Right.length;j++){
Right[j]=numbers[q+1+j];
}
int i=0;
int j=0;
while(p<=r){
if(i==Left.length){
while(j<Right.length){
numbers[p++]=Right[j++];
}
break;
}
else if(j==Right.length){
while(i<Left.length){
numbers[p++]=Left[i++];
}
break;
}
if(Left[i]<=Right[j]){
numbers[p++]=Left[i++];
}else{
numbers[p++]=Right[j++];
}
count++;
}
}
}
運作結果: