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

543

被折叠的 条评论
为什么被折叠?



