闲来无事,研究并实现啦插入排序,使用伪代码描述如下:
InsertSort:
for i <-- 1 up to Size(array) - 1
key = array[i];
for j <-- i -1 down to 0
if j>0 and key < array[j]
array[j+1] = array[j];
array[j+1] = key
上述为代码为递增排序描述,其实递减排序描述差不读,只是将key < array[j]变成key > array[j]即可。对于代码实现的实现使用type来区分是递减还是递增排序。具体代码如下:
#include <stdio.h>
typedef enum
{
NON_DECREASE,
NON_INCREASE
}t_sort;
void insert_sort(int *array, int n, t_sort type)
{
int i,j;
int key;
int move = 0; // record the times
for(i = 1; i < n; i++)
{
key = array[i];
if(type == NON_DECREASE)
{
for(j = i - 1; j >= 0 && key < array[j]; j--,move++)
array[j+1] = array[j];
}
else
{
for(j = i - 1; j >= 0 && key > array[j]; j--,move++)
array[j+1] = array[j];
}
array[j+1] = key;
}
printf ("Move %d times in insert_sort\n", move);
}
void output_arry(int *array, int n)
{
int i;
for(i = 0; i < n; i++)
{
printf ("%d ", array[i]);
}
printf ("\n");
}
int
main(void)
{
int array[] = {10,7,8,4,5,2,1,6,3,8};
printf ("The original data is: ");
output_arry(array, sizeof(array)/sizeof(int));
insert_sort(array, sizeof(array)/sizeof(int), NON_DECREASE);
//insert_sort(array, sizeof(array)/sizeof(int), NON_INCREASE);
printf ("The sorted data is: ");
output_arry(arry, sizeof(array)/sizeof(int));
return 0;
}对于递增排序测试输出结果为:
The original data is: 10 7 8 4 5 2 1 6 3 8
Move 29 times in insert_sort
The sorted data is: 1 2 3 4 5 6 7 8 8 10
对于递减排序测试输出结果为:
The original data is: 10 7 8 4 5 2 1 6 3 8
Move 15 times in insert_sort
The sorted data is: 10 8 8 7 6 5 4 3 2 1
该算法最好情况下时间复杂度为O(n),最坏情况下时间复杂度为O(n^2)。
对于相同的元素,在排序后,其相对位置不会改变,属于稳定排序。
本文介绍了一种经典的排序算法——插入排序,并提供了递增和递减排序的C语言实现。通过对比不同情况下的排序过程,展示了算法的时间复杂度及稳定性特点。
752

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



