其他
归并排序,咋归并呢?
The following article is from 爱码有道 Author 点击关注👉👉
作者丨飘渺Jam
来源丨JAVA日知录(ID:javadaily)
图解归并
步骤二:
代码实现
#include<iostream>
using namespace std;
//有序表a[first...mid]和a[mid + 1...last]的归并
void merge(int a[], int first, int mid, int last)
{
int length = last - first + 1;
int i = first;
int j = mid + 1;
int k = 0;
int *p = new int[length];
while(i <= mid && j <= last)
{
if(a[i] <= a[j])
{
p[k++] = a[i++];
}
else
{
p[k++] = a[j++];
}
}
while(i <= mid)
{
p[k++] = a[i++];
}
while(j <= last)
{
p[k++] = a[j++];
}
for(k = 0; k < length; k++)
{
a[k + first] = p[k];
}
delete [] p;
p = NULL;
}
// 递归地进行归并排序
void mergeSort(int a[], int first, int last)
{
int mid = (first + last) / 2;
if(first < last)
{
mergeSort(a, first, mid);
mergeSort(a, mid + 1, last);
merge(a, first, mid, last);
}
}
int main()
{
int a[] = {160, 150, 180, 190, 170};
int n = sizeof(a) / sizeof(a[0]);
mergeSort(a, 0, n - 1);
int i;
for(i = 0; i < n; i++)
{
cout << a[i] << " ";
}
cout << endl;
return 0;
}
点分享
点点赞
点在看