#include<iostream>
#include<string.h>
#include<stdio.h>
#include<malloc.h>
#include<stdlib.h>
#define len 10
void Show(int str[],int length);
void mergerarray(int str[],int left,int mid,int right,int temp[]);
void Merger_sort(int str[],int length);
void merger_sort(int str[],int left,int right,int temp[]);
using namespace std;
void Show(int str[],int length)
{
int i;
for(i = 0;i <length ;i++)
{
printf(" %d",str[i]);
}
}
void mergerarray(int str[],int left,int mid,int right,int temp[])
{
int i = left;
int j = mid + 1;
int m = mid;
int n = right;
int k = 0;
while(i <= m && j <= n)
{
if(str[i] < str[j]){
temp[k] = str[i];
k++;
i++;
}else{
temp[k] = str[j];
k++;
j++;
}
}
while( i < m )
{
temp[k] = str[i];
k++;
i++;
}
while( j < n){
temp[k] = str[j];
k++;
j++;
}
for( i = 0 ;i< k; i++)
{
str[left + i] = temp[i];
}
}
void merger_sort(int str[],int left,int right,int temp[])
{
if(left < right)
{
int mid = (left + right)/2;
printf("aaa\n");
merger_sort(str,left,mid,temp);
printf("bbb\n");
merger_sort(str,mid+1,right,temp);
mergerarray(str,left,mid,right,temp);
}
}
void Merger_sort(int str[],int length)
{
int *temp_array = (int *)malloc((sizeof(int )*length));
int * p = temp_array;
if( p = NULL)
{
return ;
}
merger_sort(str,0,length - 1,temp_array);
}
int main()
{
int str[len];
int i ;
for(i = 0; i < len; i++)
{
str[i] = rand()%100;
}
printf("排序前:\n");
Show(str,len);
printf("\n");
printf("排序后:\n");
Merger_sort(str,len);
Show(str,len);
return 0;
}
排序前:
41 67 34 0 69 24 78 58 62 64
排序后:
0 24 34 41 34 58 58 62 64 64Press any key to continue
排序算法之 —— 归并排序(六)
最新推荐文章于 2024-07-15 19:14:26 发布