Data structures - counting and recursion are not recursions

Insert image description here


Preface

Say important things three times!
study! study! study!
Work hard! Work hard! Work hard!


1. Non-recursive implementation of merge

Insert image description here
Insert image description here

Code:

void MergeSortNonR(int* a, int n)
{
    
    
	int* tmp = (int*)malloc(sizeof(int) * n);
	if (tmp == NULL)
	{
    
    
		perror("malloc fail");
		return;
	}

	int gap = 1;
	while (gap < n)
	{
    
    
		for (int i = 0; i < n; i += 2 * gap)
		{
    
    
			int begin1 = i, end1 = i + gap - 1;
			int begin2 = i + gap, end2 = i + 2 * gap - 1;
			// [begin1,end1] [begin2,end2] 归并
			int index = i;
			while (begin1 <= end1 && begin2 <= end2)
			{
    
    
				if (a[begin1] < a[begin2])
				{
    
    
					tmp[index++] = a[begin1++];
				}
				else
				{
    
    
					tmp[index++] = a[begin2++];
				}
			}

			while (begin1 <= end1)
			{
    
    
				tmp[index++] = a[begin1++];
			}

			while (begin2 <= end2)
			{
    
    
				tmp[index++] = a[begin2++];
			}

			// 拷贝回原数组
			memcpy(a + i, tmp + i, (2 * gap) * sizeof(int));
		}
		gap *= 2;
	}

	free(tmp);
}

2. Counting sorting

Idea:
Counting sort, also known as the pigeonhole principle, is a deformed application of the hash direct addressing method.

Insert image description here

Code:

void CountSort(int* a, int n)
{
    
    
	int min = a[0], max = a[0];
	for (size_t i = 0; i < n; i++)
	{
    
    
		if (a[i] < min)
			min = a[i];

		if (a[i] > max)
			max = a[i];
	}

	int range = max - min + 1;
	int* count = (int*)malloc(sizeof(int) * range);
	
	if (count == NULL)
	{
    
    
		perror("malloc fail");
		return;
	}
	memset(count, 0, sizeof(int) * range);

	// 统计数据出现次数
	for (int i = 0; i < n; i++)
	{
    
    
		count[a[i] - min]++;
	}

	// 排序
	int j = 0;
	for (int i = 0; i < range; i++)
	{
    
    
		while (count[i]--)
		{
    
    
			a[j++] = i + min;
		}
	}
}

Summary of features of counting sort:

  1. Counting sorting is very efficient when the data range is concentrated, but its applicable scope and scenarios are limited.
  2. Time complexity: O(MAX(N,range))
  3. Space complexity: O(range)
  4. Stability: stable

3. Analysis of complexity and stability of ordinal algorithm

Insert image description here
Insert image description here


Summarize

Say important things three times!
success! success! success!
Come on! From now on~

Guess you like

Origin blog.csdn.net/mdjsmg/article/details/133498857