数据结构_合并排序

来源:互联网 发布:怎么找淘宝店铺微淘 编辑:程序博客网 时间:2024/05/26 16:01

// 数据结构_合并排序.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include <stdio.h>
#include <stdlib.h>

/*合并排序又叫归并排序,它采用分治法,递归来进行排序,将原问题分解成一系列的子问题
递归求各个子问题的解,将子问题的结果合并成原问题的解
算法导论中的伪代码
MERGE(A,p,q,r)
1 n1 = q - p + 1
2 n2 = r - q
3 create arrays L[1...n1+1] and R[1...n2+1]
4 for i <- 1 to n1
5 do L[i] <- A[p+i-1]
6 for j <- 1 to n2
7 do R[j] <- A[q+j]
8 L[n1+1] <- 最大值
9 R[n2+1] <- 最大值
10 i = 1
11 j = 1
12 for k <- p to r
13 do if L[i] <= R[j]
14  then A[k] <- L[i]
15   i <- i + 1
16  else A[k] <- R[j]
17   j = j + 1

MERGE-SORT(A,p,r)
1 if p < r
2  then q <- |_(p + r)/2_|
3  MERGE-SORT(A,p,q)
4  MERGE-SORT(A,q+1,r)
5  MERGE(A,p,q,r)
*/
#define arrary_length 100

int paixu_charu(int a[],int p,int q,int r){

 int n1 = 0,n2 = 0,i = 0,j = 0,k = 0;

 int *L,*R;

 n1 = q - p + 1;

 n2 = r - q;

 /*动态创建归并排序两个数组*/

 L = (int *)malloc(sizeof(int)*(n1+1));

 R = (int *)malloc(sizeof(int)*(n2+1));

 /*将待排序数据的数据拷贝到左右数组中*/
 /*这里我们跟伪算法有点都不一样,因为,我现在使用的数组的下表从0开始,伪代码从1开始
 这里L[i] = a[i+p]这个地方我们使用i+p-1,因为从0开始,默认就少1,下面同理,R[j] = a[q+j],因为从0开始,所以这里我们加1
 */
 for(i = 0; i < n1;i++){
 
  L[i] = a[i+p];

 }
 for(j = 0; j < n2; j++){
 
  R[j] = a[q+j+1];

 }
 
 /*将左右数组的尾赋最大值*/

 L[n1] = (1 << 31) - 1;
 R[n2] = (1 << 31) - 1;

 i = 0;
 j = 0;
 /**/
 for(k = p; k < r+1;k++){
 
  if(L[i] <= R[j]){
  
   a[k] = L[i];
   i = i + 1;
  }
  else
  {
   a[k] = R[j];
   j = j + 1;
  
  }

 }

 return 0;

}

int paixu_sort(int a[],int p, int r){

 if(p < r){

  int q = (p + r) / 2;

  paixu_sort(a,p,q);

  paixu_sort(a,q+1,r);

  paixu_charu(a,p,q,r);
  
 }

 return 0;


}

int _tmain(int argc, _TCHAR* argv[])
{
 int a[arrary_length];
 
 int icycle = 0;

 printf("hebin paixu before:\n");

 for(icycle = 0; icycle < arrary_length;icycle++){
 
  a[icycle] = (icycle + 1 + rand()) / 2 + rand();

  printf("%d ",a[icycle]);
 
 }

 printf("\n");

 /*这里,我们默认从1到100,如果使用数组使用的是从0到99*/
 paixu_sort(a,0,99);

 printf("hebin paixu after:\n");

 for(icycle = 0; icycle < arrary_length;icycle++){
 
  printf("%d ",a[icycle]);
 
 }

 return 0;
}