每個(gè)人都曾試圖在平淡的學(xué)習(xí)、工作和生活中寫一篇文章。寫作是培養(yǎng)人的觀察、聯(lián)想、想象、思維和記憶的重要手段。寫范文的時(shí)候需要注意什么呢?有哪些格式需要注意呢?這里我整理了一些優(yōu)秀的范文,希望對(duì)大家有所幫助,下面我們就來了解一下吧。
歸并排序算法c語言實(shí)現(xiàn) 歸并排序c語言算法詳解篇一
歸并排序算法是采用分治法的一個(gè)非常典型的應(yīng)用。下面小編為大家整理了c++歸并排序算法實(shí)例,希望能幫到大家!
歸并排序的思想是將一個(gè)數(shù)組中的數(shù)都分成單個(gè)的`;對(duì)于單獨(dú)的一個(gè)數(shù),它肯定是有序的,然后,我們將這些有序的單個(gè)數(shù)在合并起來,組成一個(gè)有序的數(shù)列。這就是歸并排序的思想。它的時(shí)間復(fù)雜度為o(n*logn)。
代碼實(shí)現(xiàn)
復(fù)制代碼 代碼如下:
#include
using namespace std;
//將有二個(gè)有序數(shù)列a[first...mid]和a[mid...last]合并。
void mergearray(int a[], int first, int mid, int last, int temp[])
{
int i = first, j = mid + 1;
int m = mid, n = last;
int k = 0;
while (i <= m && j <= n)
{
if (a[i] <= a[j])
temp[k++] = a[i++];
else
temp[k++] = a[j++];
}
while (i <= m)
temp[k++] = a[i++];
while (j <= n)
temp[k++] = a[j++];
for (i = 0; i < k; i++)
a[first + i] = temp[i];
}
void mergesort(int a[], int first, int last, int temp[])
{
if (first < last)
{
int mid = (first + last) / 2;
mergesort(a, first, mid, temp); //左邊有序
mergesort(a, mid + 1, last, temp); //右邊有序
mergearray(a, first, mid, last, temp); //再將二個(gè)有序數(shù)列合并
}
}
bool mergesort(int a[], int n)
{
int *p = new int[n];
if (p == null)
return false;
mergesort(a, 0, n - 1, p);
[] p;
return true;
}
int main()
{
int arr[] = {2, 1, 4};
mergesort(arr, 3);
for (int i = 0; i < 3; ++i)
{
cout<<arr[i]<<" ";
}
cout<<endl;
}
s("content_relate");【c++歸并排序算法實(shí)例】相關(guān)文章:
c++插入排序算法實(shí)例
11-04
c語言實(shí)現(xiàn)歸并排序算法實(shí)例
11-21
c++實(shí)現(xiàn)自頂向下的歸并排序算法
10-01
c++實(shí)現(xiàn)自底向上的歸并排序算法
10-01
c語言冒泡排序算法實(shí)例
11-21
c語言插入排序算法及實(shí)例代碼
10-08
c語言奇偶排序算法詳解及實(shí)例代碼
10-04
c語言中使用快速排序算法對(duì)元素排序的實(shí)例
10-02
c++ 排序插入排序詳解
10-04
【本文地址:http://www.aiweibaby.com/zuowen/2729139.html】