1. 程式人生 > >常見排序之歸併排序

常見排序之歸併排序

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

#define ELEMENT_CNT 10

void merge(int *array,int low,int mid,int high)
{
int i,k;
int left_low = low;
int left_high = mid;
int right_low = mid+1;
int right_high = high;

int *temp = (int *)malloc((high-low+1)*sizeof(int));

if(!temp)
{
return;
}


for(k = 0; left_low <= left_high && right_low <= right_high; k++)
{
if(array[left_low] < array[right_low])
{
temp[k] = array[left_low++];
}
else
{
temp[k] = array[right_low++];
}

}

if(left_low <= left_high)
{
for(i = left_low; i <= left_high; i++)
{
temp[k++] = array[i];
}
}

if(right_low <= right_high)
{
for(i = right_low; i <= right_high; i++)
{
temp[k++] = array[i];

}
}

for(i = 0; i < (high-low+1); i++)
{
array[low+i] = temp[i];
}

free(temp);
return;

}

void merge_sort(int *array,int low,int high)
{
int mid = 0;

if(low < high)
{
mid = (low+high)/2;

merge_sort(array,low,mid);
merge_sort(array,mid+1,high);
merge(array,low,mid,high);

}

}


void trease_array(int *array)
{
int i;

for(i = 0; i < ELEMENT_CNT; i++)
{
printf("%d\t",array[i]);
}
}


int main(void)
{
int array_sort[ELEMENT_CNT] = {6,4,7,3,8,2,9,1,5,0};

trease_array(array_sort);

merge_sort(array_sort,0,ELEMENT_CNT-1); //此處長度為ELEMENT_CNT-1

trease_array(array_sort);

return 0;
}