数据结构 归并排序(Merge Sort) 详解 附C++代码实现:

た 入场券 2024-02-19 18:11 190阅读 0赞

目录

简介:

算法描述:

代码实现:

总结:


简介:

归并排序是典型的递归思想的应用,将一个序列分为两个子序列,叫做二路归并,是一种稳定的排序算法,时间复杂度为:O(nlogn)

算法描述:

849589-20171015230557043-37375010.gif

  • 把长度为n的输入序列分成两个长度为n/2的子序列;
  • 对这两个子序列分别采用归并排序;
  • 将两个排序好的子序列合并成一个最终的排序序列。

代码实现:

  1. #include<iostream>
  2. #include<stdio.h>
  3. #include<stdlib.h>
  4. #include<time.h>
  5. using namespace std;
  6. #define num 10000
  7. void mergearray(int a[],int first,int mid,int last,int t[])
  8. {
  9. int i=first,j=mid+1;
  10. int n=mid,m=last;
  11. int k=0;
  12. while(i<=n&&j<=m)
  13. {
  14. if(a[i]<=a[j])
  15. t[k++]=a[i++];
  16. else
  17. t[k++]=a[j++];
  18. }
  19. while(i<=n)
  20. {
  21. t[k++]=a[i++];
  22. }
  23. while(j<=m)
  24. {
  25. t[k++]=a[j++];
  26. }
  27. for(i=0;i<k;i++)
  28. {
  29. a[first+i]=t[i];
  30. }
  31. }
  32. void mergesort(int a[],int first,int last,int t[])
  33. {
  34. if(first<last)
  35. {
  36. int mid=(first+last)/2;
  37. mergesort(a,first,mid,t);
  38. mergesort(a,mid+1,last,t);
  39. mergearray(a,first,mid,last,t);
  40. }
  41. }
  42. int MergeSort(int a[],int len)
  43. {
  44. int *temp=new int [len];
  45. if(temp==NULL)
  46. return 0;
  47. else
  48. mergesort(a,0,len-1,temp);
  49. delete []temp;
  50. return 1;
  51. }
  52. int main()
  53. {
  54. clock_t start,end;
  55. start=clock();
  56. freopen("out_arr.txt","r",stdin);
  57. freopen("out归并排序.txt","w",stdout);
  58. int arr[num];
  59. int n=num;
  60. for(int i=0;i<n;i++)
  61. {
  62. scanf("%d",&arr[i]);
  63. }
  64. MergeSort(arr,n);
  65. for(int i=0;i<n;i++)
  66. {
  67. printf("%5d ",arr[i]);
  68. if((i+1)%50==0)
  69. printf("\n");
  70. }
  71. end=clock();
  72. printf("归并排序耗时:%dms\n",(float)(end-start)*1000.0/CLOCKS_PER_SEC);
  73. return 0;
  74. }

watermark_type_ZmFuZ3poZW5naGVpdGk_shadow_10_text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3FxXzQxMzI1Njk4_size_16_color_FFFFFF_t_70

watermark_type_ZmFuZ3poZW5naGVpdGk_shadow_10_text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3FxXzQxMzI1Njk4_size_16_color_FFFFFF_t_70 1

总结:

归并排序是一种稳定的排序方法。和选择排序一样,归并排序的性能不受输入数据的影响,但表现比选择排序好的多,因为始终都是O(nlogn)的时间复杂度。代价是需要额外的内存空间。

小伙伴们,如果还看不懂,在评论区留言,乐意解答。

#

发表评论

表情:
评论列表 (有 0 条评论,190人围观)

还没有评论,来说两句吧...

相关阅读

    相关 归并排序merge sort

    归并排序(Merge sort)是建立在归并操作上的一种有效的排序算法。该算法是采用分治法(Divide and Conquer)的一个非常典型的应用。(出自[维基百科][Li