1、冒泡排序:
将相邻两个数比较,将小的调到前头,冒泡排序是稳定的。
void BubbleSort(int a[],int n)
{
for(int i=0;i<n-1;i++)
{
for(int j=0;j<n-1-i;j++)
{
if(a[j+1]<a[j])
{
int temp=a[j+1];
a[j+1]=a[j];
a[j]=temp;
}
}
}
}
2、选择排序:
选择排序开始的时候,扫描整个列表,找到它的最小元素然后和第一个元素交换,将最小元素放到它在有序表中的最终位置上。然后我们从第二个元素开始扫描列表,找到最后n-1个元素中的最小元素,再和第一个元素交换位置,把第二小的元素放在它的最终位置上。选择排序是稳定的。
void SelectionSort(int a[], int n)
{
for(int i=0;i<n-1;i++)
{
int min=i;
for(int j=i+1;j<n;j++)
{
if(a[j]<a[min])
min=j;
}
if(min!=i)
{
int temp=a[min];
a[min]=a[i];
a[i]=temp;
}
}
}
3、堆排序:
堆排序是不稳定的
#include<stdio.h>
#define N 10
void HeapAdjust(int a[],int s,int m)
{
int rc=a[s];
for(int j=2*s+1;j<=m;j=2*j+1)
{
if(j<m && a[j]<a[j+1])
++j;
if(rc>=a[j])
break;
a[s]=a[j];
s=j;
}
a[s]=rc;
}
int main()
{
int a[N];
for(int i=0;i<N;i++)
scanf("%d",&a[i]);
for(int i=N/2-1;i>=0;--i)
<pre name="code" class="cpp"> HeapAdjust(a,i,N-1);
for(int i=N-1;i>0;--i)
{
int temp=a[0];
a[0]=a[i];
a[i]=temp;
HeapAdjust(a,0,i-1);
}
for(int i=0;i<N;i++)
printf("%d ",a[i]);
printf("/n");
return 0;
}
4、直接插入排序:
基本操作是将一个记录插入到已排好序的有序表中,从而得到一个新的、记录数增1的有序表。
void InsertionSort(int a[],int n)
{
for(int i=1;i<n;i++)
{
int temp=a[i];
int j=i-1;
while(j>=0 && a[j]>temp)
{
a[j+1]=a[j];
j--;
}
a[j+1]=temp;
}
}
5、希尔排序:
#include<stdio.h>
#define N 10 //待排序数据的条数
#define M 3 //增量序列元素个数 0<=M<=log2(n-1)
void ShellInsert(int *a, int n, int dk) //对N条数据作一趟希尔排序
{
for(int i=dk;i<n;i++)
{
if(a[i]<a[i-dk]) //需将*(a+i)插入有序增量子表
{
int temp=a[i]; //暂存在temp中
for(int j=i-dk;j>=0 && temp<a[j];j-=dk)
a[j+dk]=a[j]; //记录后移,查找插入位置
a[j+dk]=temp; //插入
}
}
}
void ShellSort(int *a, int n, int dlat[], int t) //按增量序列dlta[0..M]对数据作希尔排序
{
for(int k=0;k<t;k++)
ShellInsert(a,n,dlat[k]); //一趟增量为dlta[k]的插入排序
}
void main()
{
int a[N];
int dlat[M]={/*1023,511,255,127,63,31,15,*/7,3,1}; /*增量序列 dlta[k]=1/2(3^(t-k)-1)*/
for(int i=0;i<N;i++)
scanf("%d",&a[i]); //输入数据
ShellSort(a,N,dlat,M); //调用希尔排序函数
for(int i=0;i<N;i++)
printf("%d ",a[i]);
printf("/n");
}
6、快速排序:
快速排序是不稳定的
#include<stdio.h>
#define N 10 //待排序数据的条数
int Partition(int *a, int low, int high) //求枢轴
{
int pivotkey=a[low]; //作枢轴记录
while(low<high) //从表的两端交替地向中间扫描
{
while(low<high && a[high]>=pivotkey)
--high;
a[low]=a[high]; //将比枢轴记录小的记录移到低端
while(low<high && a[low]<=pivotkey)
++low;
a[high]=a[low]; //将比枢轴记录大的记录移到高端
}
a[low]=pivotkey; //枢轴记录到位
return low; //返回枢轴位置
}
void QSort(int *a, int low, int high)
{
if(low<high)
{
int pivotloc=Partition(a,low,high);
QSort(a, low, pivotloc-1);
QSort(a, pivotloc+1, high);
}
}
void main()
{
int a[N];
for(int i=0;i<N;i++)
scanf("%d",&a[i]); //输入数据
QSort(a,0,N-1); //调用排序函数
for(int i=0;i<N;i++)
printf("%d ",a[i]);
printf("/n");
}