当前位置:网站首页>Merge sort (recursive and iterative Implementation)

Merge sort (recursive and iterative Implementation)

2022-06-22 20:02:00 Just one word

Recursive implementation :B Station turtle video
https://www.bilibili.com/video/BV1jW411K7yg?p=95

#include <stdio.h>
#define MAXSIZE 10

//  Merge , And store the final results in list1 in 
void merging(int *list1, int list1_size, int *list2, int list2_size)
{
    
	int i, j, k, m;
	int temp[MAXSIZE];

	i = j = k = 0;

	while( i < list1_size && j < list2_size )
	{
    
		if( list1[i] < list2[j] )
		{
    
			temp[k++] = list1[i++];
		}
		else
		{
    
			temp[k++] = list2[j++];
		}
	}

	while( i < list1_size )
	{
    
		temp[k++] = list1[i++];
	}

	while( j < list2_size )
	{
    
		temp[k++] = list2[j++];
	}

	for( m=0; m < (list1_size + list2_size); m++ )
	{
    
		list1[m] = temp[m];
	}
}

void MergeSort(int k[], int n)
{
    
	if( n > 1)
	{
     
		int *list1 = k;
		int list1_size = n/2;
		int *list2 = k + n/2;
		int list2_size = n - list1_size;

		MergeSort(list1, list1_size);
		MergeSort(list2, list2_size);

		merging(list1, list1_size, list2, list2_size);
	}
}

int main()
{
    
	int i, a[10] = {
    5, 2, 6, 0, 3, 9, 1, 7, 4, 8};

	MergeSort(a, 10);

	printf(" The result of sorting is :");
	for( i=0; i < 10; i++ )
	{
    
		printf("%d", a[i]);
	}
	printf("\n\n");

	return 0;
}

Iterative implementation :
https://www.bilibili.com/video/BV1jW411K7yg?p=96

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

#define MAXSIZE 10

void MergeSort(int k[], int n)
{
    
	int i, next, left_min, left_max, right_min, right_max;
	int *temp = (int *)malloc(n * sizeof(int));

	for( i=1; i < n; i*=2 ) 
	{
    
		for( left_min=0; left_min < n-i; left_min = right_max )
		{
    
			right_min = left_max = left_min + i;
			right_max = left_max + i;

			if( right_max > n )
			{
    
				right_max = n;
			}

			next = 0;

			while( left_min < left_max && right_min < right_max )
			{
    
				if( k[left_min] < k[right_min] )
				{
    
					temp[next++] = k[left_min++];
				}
				else
				{
    
					temp[next++] = k[right_min++];
				}
			}

			while( left_min < left_max )
			{
    
				k[--right_min] = k[--left_max];
			}

			while( next > 0 )
			{
    
				k[--right_min] = temp[--next];
			}
		}
	}
}

int main()
{
    
	int i, a[10] = {
    5, 2, 6, 0, 3, 9, 1, 7, 4, 8};

	MergeSort(a, 10);

	printf(" The result of sorting is :");
	for( i=0; i < 10; i++ )
	{
    
		printf("%d", a[i]);
	}
	printf("\n\n");

	return 0;
}

原网站

版权声明
本文为[Just one word]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/173/202206221828271810.html