方法概览:
- 内部排序:
1.插入类排序 ①直接插入排序 ②希尔排序法
2.选择类排序 ①直接选择排序法 ②堆排序法
3.交换类排序 ①冒泡排序法 ②快速排序法
4.归并类排序
5.基数排序
- 外部排序
二路合并排序 多路替代选择合并排序
下面开始从易到难逐个总结啦~
一.插入类排序
1.插入类排序:向有序区间中插入一个元素的排序过程
2.直接插入排序:
排序思想:设有n个数据等待排序,区间a[0]到a[n-1]。 起始时,有序序列为首元素a[0],无序序列为a[1]到a[n-1]。
遍历无序区间所以元素,每次取出无序区间的第一个元素a[i]与有序区间的元素比较,将a[i]插入有序区间中合适的位置。
如果待插入的元素与有序序列中的某个元素相等,则将待插入元素插入到相等元素的后面。
最终,无序序列变为空,得到一个排序好的有序序列。
实现:
#include<stdio.h>
#include<stdlib.h>
void InsertSort(int a[],int n);
void PrintArray(int a[],int n);
int main(void)
{
int n; //n为待排序序列长度
int *arr; //arr为待排序的序列首元素指针(数组名)
int loop; //数组存入元素时的循环变量
printf("Please enter the length of the out-of-order sequence.\n");
scanf("%d",&n);
arr=(int*)malloc(n*sizeof(int)); //为数组arr开辟空间
printf("Please enter the element of the out-of-order sequence one by one.\n");
for(loop=0;loop<n;loop++)
{
scanf("%d",&arr[loop]);
}
// int n=5;
InsertSort(arr,n); //调用直接排序函数进行排序
PrintArray(arr,n);
}
/*直接选择排序函数*/
void InsertSort(int a[],int n)
{
int i,j,x;
for(i=1;i<n;i++) // 遍历无序序列
{
x=a[i]; //取出无序序列的第一个元素,放在x里
for(j=i-1;j>-1;j--) //遍历有序序列,给x找到一个合适的位置
{
if(a[j]>x) //将有序序列中大于x的元素后移,
a[j+1]=a[j];
else
break;
}
a[j+1]=x; //将x放入有序序列中的合适位置
}
}
/*数组元素输出函数*/
void PrintArray(int a[],int n)
{
int loop;
for(loop=0;loop<n;loop++)
{
printf("%8d",a[loop]);
}
}
2.希尔排序法
【还在学习中呐,随后再更新啦】
今天先写到这里,第一次写博客, 不足的地方请大家多多批评指正!谢谢大家~
欢迎大家关注我啦~我叫微微发亮