Introduce to algorithm-------pseudo code to C/C++ code(Chapter 2)

本文详细介绍了两种经典的排序算法:插入排序和归并排序。插入排序通过将每个元素插入到已排序序列中的适当位置来工作。而归并排序则采用分治策略,将数组分成两部分递归地进行排序,然后合并两个有序子数组。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Insertion sort:

The basic idea of insertion sort is to insert one into a sorted sequence. So the step is very simple, 

insert the next element into the former sequence which is already sorted in the same order. The first step 

deals with the second element, regarding the first one as sorted.

And here is the code in C/C++:

template <typename T>
void insertion_sort (T* A, int length)
{
	int			i, j, value, temp;
	for (i = 1; i < length; ++i)
	{
		j= i - 1;
		value = A[i];
		/* if former value is larger than the one
		  to be inserted, move back */
		while (j >= 0 && A[j] > value)
			A[j + 1] = A[j],
			--j;
		//place the value at the appropriate place
		A[j + 1] = value;
	}
}

Merge_sort:

This algorithm applies divide-and-conquer strategy. The basic idea is divide the original problem into two small sub-problems.

Under this circumstance, he input array is divided into two small arrays by the algorithm which respectively calls the same algorithm.

Then, merge this two sorted sub-arrays.

And here is the code in C/C++:

template <typename T>
void merge_sort (T *A, int p, int r)
{
	if (p < r)
	{
		int 	q = (p + r) / 2;
		merge_sort (A, p, q);
		merge_sort (A, q + 1, r);
		merge (A, p, q, r);
	}
}

//merge two sorted arrays
template <typename T>
void merge (T* A, int p, int q, int r)
{
	if (q >= p && r > q)
	{
		const 	int 	MAX_LENGTH = 256;
		int 	n1 = q - p + 1, n2 = r - q;
		T 		L[MAX_LENGTH], R[MAX_LENGTH];
		
		//set L[] and R[] respectively to two sub-arrays
		for (int i = 0; i < n1; ++i)
			L[i] = A[p + i];
		for (int i = 0; i < n2; ++i)
			R[i] = A[q + 1 + i];
		
		L[n1] = INT_MAX;
		R[n2] = INT_MAX;
		
		//place elements into A[]
		int 	i = 0, j = 0;
		for (int k = p; k <= r; ++k)
			if (L[i] < R[j])
				A[k] = L[i],
				++i;
			else 
				A[k] = R[j],
				++j;
	}
}

For detail information, see Introduce to algorithm (Third Edition);

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值