各種排序 冒泡,歸併,快排等實現與對比。

2021-06-22 01:06:17 字數 1843 閱讀 4525

排序的呼叫方法:n為陣列,測試了5萬條資料。

long starttime=system.currenttimemillis();   //獲取開始時間

system.out.println("排序開始:"+ starttime);

sort(n);

long endtime=system.currenttimemillis(); //獲取結束時間

首先氣泡排序:

/**

* 排序

* @param num要排序的陣列

*/public static void sort(int num)

if(num[i] > num[j])

}} }

歸併排序:

public void merge(int num,int s, int e, int result)

int m = (e+s)/2;

int p = new int[e+1];

merge(num,s,m,p);

merge(num,m+1,e,p);

sort(p,s,m,e,result);

} /**

* 左右合併排序

* @param num

* @param s

* @param m

* @param e

* @param result

*/public void sort(int num, int s, int m, int e, int result)else

} while(ss <= m)

while(kk <= e)

}

快速排序:

/**

* 排序

* @param num

* @param low

* @param height

*/public static void sort(int num, int low, int height) }

public static int adjust(int num, int low, int height)

num[low] = num[height];

//從低位迴圈比較直到發現大於中軸的數

while(low < height && pivote - num[low] >= 0)

num[height] = num[low];

} //將中軸賦到當前的位置

num[low] = pivote;

return low;

}

根據陣列中最大值建立乙個陣列。將原陣列對應的數放入新陣列中所在的位置。

缺點,0無法排序。

public static void space(int array)

} int temp = new int[max+1];

for (i = 0; i < l; i++)

temp[array[i]] = array[i];

int j = 0;

int max1 = max + 1;

for(i=0; i0)

} }

總結:

氣泡排序耗時9500ms-11000ms

歸併排序耗時8000ms-9200ms

快速排序耗時10ms以內

是的,你沒看錯差距就是如此之大

歸併排序的優點是穩定,但是我對這個穩定理解不深。大致是說相等相鄰的兩個數,在歸併排序時不會改變兩個數的位置(按照輸入的先後排),

快速排序有可能會改變位置。

排序 冒泡,快排,歸併。

1 冒泡 就是每次相鄰的比較,較大的移到後面,一次後就移動最大的到最後面了。include void maopao int a,int len void main int len sizeof a sizeof a 0 maopao a,len for int x1 0 x12 快速排序,用遞迴來理...

排序演算法介紹及實現 選擇 冒泡 歸併 快排等

記錄一下最近學習的各種排序演算法。插入排序 氣泡排序 歸併排序 快速排序 選擇排序是最簡單且容易想到的排序方法。它把輸入值 以下均以列表為例 分為兩個部分 已排序 和 未排序部分。先看一組偽 找到餘下值中最小的索引值,與第i個值交換。若沒找到則不變 temp numbers i numbers i ...

C 實現各種排序 快排 插排 冒泡

1 插入排序 插入排序 主要思想 將陣列中的第乙個數認為是有序排列,剩下的n 1個數與第乙個數比較,再進行排序 有兩層迴圈,第一層控制排序的趟數,第二層控制每一趟比較的個數 include using namespace std int main for int i 0 i 10 i cin a i...