日常编程笔记 | 2022.10.1 | 归并排序_一无序列

极大数

在这里插入图片描述

又是数组下标访问越界了

在这里插入图片描述

当i或j超过右端点时,又在if判断中被拿来当下标参与比较,然后进入arr数列了

还有一处
在这里插入图片描述
左边数列的右端点就是中间的数,不应该用mid + 1

mid的计算

在这里插入图片描述

这里mid不能这样计算,否则会出现这样的情况

在这里插入图片描述

大量重复数字

在这里插入图片描述

在这里插入图片描述本来想在i或j超过原来范围的时候强制把它转为右端点,但这样的话,每次赋值就都赋两个数列中,第一个被遍历完的数列的右端点了

C源码

//this function uses Divid-and-Conquer algorithm to sort unordered array 

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

#define N 10

void Sort(int*a, int left, int right);//to divide the array into the smallest ordered pieces

void Merge(int*a, int left, int mid, int right);//to merge the ordered two pieces into a larger one

int main()
{
	srand((unsigned int)time(0));//initialize the seed
	int *a = (int*)malloc(sizeof(int)*N);//to create a test array
	
	int  i;
	for(i = 0; i < N; i++)
	{
		a[i] = rand()%200 - 100;//to assign a random number from -100 to 100 to a[i]
		
	}
	
	Sort(a, 0, N - 1);//sort the array
	
	for(i = 0 ; i < N; i++)//print the array
	{
		printf("%d ", a[i]); 	
	}
	
	
	return 0;
}

void Sort(int*a, int left, int right)
{
	if(left >= right)//if divide the array into the smallest pieces
		return;
	int mid = left + (right - left)/2;//calculate the mid point
	
	Sort(a, left, mid);//sort the left side
	Sort(a, mid + 1, right);//sort the right side
	
	Merge(a, left, mid, right);//merge from bottom to top
}

void Merge(int*a, int left, int mid, int right)
{
	int size = right - left + 1;//the size of the array to store the ordered array
	
	int*arr = (int*)malloc(sizeof(int)*size); //allocate space to arr
	
	int i = left, j = mid + 1, k = 0; //i-the index of the left array
									//j-the index of the right array
									//k-the index of the new array
	for(k = 0; k < size; k++)
	{	
		if(i <= mid && j <= right)//if both of the two arrays are not traversed
		{
			//assign the smaller one to arr earlier, thus the arr is in increasing order
			if(a[i] <= a[j])
			{
				arr[k] = a[i];
				i++;
			}
			
			else if(a[j] < a[i])
			{
  				arr[k] = a[j];
				j++;
				
			}
		}
		//if one of the array is traversed, just assign the left part of the other array to arr
		else if(i > mid && j <= right)
		{
			arr[k] = a[j++];
		}
		
		else if(j > right && i <= mid)
		{
			arr[k] = a[i++];
		}

	}
	//assign the value of arr one by one to a, which are already in increasing order
	for(k = left; k <= right; k++)
	{
    	a[k] = arr[k - left];
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值