铛铛铛,小伙伴们o(*^@^*)o,本文主要介绍内排序算法!
那么问题来了:什么是内排序算法和外排序算法?
内排序:排序表放在内存中处理,不涉及数据的内外存交换,适用于元素个数少的表
外排序:排序表在排序过程中涉及数据的内外存交换,适用于元素个数很多,不能一次放入内存的大表。
目录
首先编写顺序表操作程序seqlist.cpp
#include<stdio.h>
#define max 100
typedef int keytype;
typedef char infotype;
typedef struct
{
keytype key;
infotype data;
}rectype;
void swap(rectype &x,rectype &y){//x与y交换
rectype tmp=x;
x=y;
y=tmp;
}
void creatlist(rectype r[],keytype keys[],int n){//创建顺序表
for(int i=0;i<n;i++)
{
r[i].key=keys[i];
}
}
void displist(rectype r[],int n){//输出顺序表
for(int i=0;i<n;i++)
printf("%d ",r[i].key);
printf("\n");
}
//针对堆排序的程序
void creatlist1(rectype r[],keytype keys[],int n){
for(int i=1;i<n;i++)
r[i].key=keys[i-1];
}
void displist1(rectype r[],int n){//输出顺序表
for(int i=1;i<=n;i++)
printf("%d ",r[i].key);
printf("\n");
}
一、直接插入排序:
#include"seqlist.cpp"
void insertsort(rectype r[],int n)
{
int i,j;
rectype tmp;
for(int i=1;i<n;i++)
{
printf("i=%d,插入%d,插入结果:",i,r[i].key);
if(r[i].key<r[i-1].key)//反序时
{
tmp=r[i];
j=i-1;
do{//找r[i]的插入位置
r[j+1]=r[j];//将关键字大于r[i].key的记录后移
j--;
}while(j>=0&&r[i].key>tmp.key);
r[j+1]=tmp;//在j+1处插入r[i]
}
displist(r,n);
}
}
int main()
{
int n=10;
keytype a[]={9,8,7,6,5,4,3,2,1,0};
rectype r[max];
creatlist(r,a,n);
printf("排序前:");
displist(r,n);
insertsort(r,n);
printf("排序后:");
displist(r,n);
return 1;
}
二、折半插入排序
#include"seqlist.cpp"
void bininsertsort(rectype r[],int n)
{
int i,j,low,high,mid;
rectype tmp;
for(int i=1;i<n;i++)
{
if(r[i].key<r[i-1].key)//反序时
{
printf("i=%d,插入%d,插入结果:",i,r[i].key);
tmp=r[i];//将r[i]保存到tmp中
low=0;high=i-1;
while(low<=high)//在r[low...high]中查找插入的位置
{
mid=(low+high)/2;//取中间位置
if(tmp.key<r[mid].key)
high=mid-1;//插入点在左半区
else
low=mid+1;//插入点在右半区
}//找位置high
for(j=i-1;j>=high+1;j--)//集中进行元素后移
r[j+1]=r[j];
r[high+1]=tmp;//插入tmp
}
displist(r,n);
}
}
int main()
{
int n=10;
rectype r[max];
keytype a[]={9,8,7,6,5,4,3,2,1,0};
creatlist(r,a,n);
printf("排序前:");
displist(r,n);
bininsertsort(r,n);
printf("排序后:");
displist(r,n);
return 1;
}
三、希尔排序
#include"seqlist.cpp"
void shellsort(rectype r[],int n)
{
int i,j,d;
rectype tmp;
d=n/2;//增量置初值
while(d>0)
{
for(i=d;i<n;i++)//对所有组采用直接插入排序
{
tmp=r[i];//对相隔d个位置一组采用直接插入排序
j=i-d;
while(j>=0&&tmp.key<r[j].key)
{
r[j+d]=r[j];
j=j-d;
}
r[j+d]=tmp;
}
printf("d=%d:",d);
displist(r,n);
d=d/2;//减小增量
}
}
int main()
{
int n=10;
rectype r[max];
keytype a[]={9,8,7,6,5,4,3,2,1,0};
creatlist(r,a,n);
printf("排序前:");
displist(r,n);
shellsort(r,n);
printf("排序后:");
displist(r,n);
return 1;
}
四、冒泡排序
#include"seqlist.cpp"
void bubblesort(rectype r[],int n)
{
int i,j;
bool exchange;
for(i=0;i<n-1;i++)
{
exchange=false;
for(j=n-1;j>i;j--)//归位r[i],循环n-i-1次
if(r[j].key<r[j-1].key)//相邻两个元素反序
{
swap(r[j],r[j-1]);//将这两个元素交换
exchange=true;
}
printf("i=%d:归位元素%d,排序结果:",i,r[i].key);
displist(r,n);
if(!exchange) //本趟没有交换,中途结束算法
return;
}
}
int main()
{
int n=10;
rectype r[max];
keytype a[]={6,8,7,9,0,1,3,2,4,5};
creatlist(r,a,n);
printf("排序前:");
displist(r,n);
bubblesort(r,n);
printf("排序前:");
displist(r,n);
return 1;
}