冒泡排序
void Bubble_Sort(int array[],int N)
{
for(int p=N-1;p>0;p--)
{
int flag=0;
for(int i=0;i<p;i++)
{
if(array[i]>array[i+1])
{
swap(array,i,i+1);
flag=1;
}
}
if(flag==0)
{
//printf("%d have sort\n",N-p);
break;
}
}
}
插入排序
void Insert_Sort(int array[],int N)
{
for(int i=1;i<N;i++)/*i表示需要排序的位置点*/
{
int j;
int temp=array[i];
/*当某个位置的前一个位置小于等待排序的元素,当前位置为插入的位置点*/
for(j=i;j&&array[j-1]>temp;j--)/*j表示插入位置*/
{
array[j]=array[j-1];
}
array[j]=temp;
}
}
希尔排序(插入排序的优化,每隔D个元素的插入排序)
void Shell_Sort(int array[],int N)
{
for(int D=N/2;D>0;D--)
{
for(int i=D;i<N;i++)
{
int j;
int temp=array[i];
for(j=i;j>0&&array[j-D]>temp;j-=D)
array[j]=array[j-D];
array[j]=temp;
}
}
}
堆排序
/*i表示根接点,N表示数据长度*/
void Heap_Adjust(int array[],int i,int N)
{
}
void Heap_Sort(int array[],int N)
{
/*1、建立最大堆*/
for(int i=N/2-1;i>=0;i--)
{
Heap_Adjust(array,i,N);
}
/*2、交换堆顶元素和最后元素*/
for(int i=N-1;i>0;i--)
{
swap(array,0,i);
Heap_Adjust(array,0,i);
}
}
快速排序
现实应用中最快的算法。思想:分而治之。
步骤:选主元(三数取中、子集划分,伪代码实现 )
void Quick_Sort(ElementType A[],int N)
{
if(N<2) return;
pivot=从A[]中选择一个主元;
将A[]以pivot为界限分成左右两个子集;
s[1]={A[i]|A[i]<=pivot};
s[2]={A[i]|A[i]>=pivot};
A[]=Quick_Sort(A1,N1)并上pivot并上Quick_Sort(A2,N2);
}
/*一次归并排序*/
void Merge(int array[],int temp[],int first,int last)
{
if(first>=last)
return;
int mid=(first+last)/2;
//int length=last-first+1;
int index=first;
int start=first;
int nextfirst=mid+1;
Merge(array,temp,first,mid);
Merge(array,temp,nextfirst,last);
while(first<=mid&&nextfirst<=last)/*对比错误的写法两个while条件array[first]<array[nextfirst]&&first<=mid&&nextfirst<=last*/
{
if(array[first]<array[nextfirst])
{
temp[index++]=array[first++];
}else
{
temp[index++]=array[nextfirst++];
}
}
while(first<=mid)
temp[index++]=array[first++];
while(nextfirst<=last)
temp[index++]=array[nextfirst++];
memcpy(&array[start],&temp[start],(last-start+1)*sizeof(int));/*注意要乘以sizeof(int)*/
return;
}
void Merge_Sort(int array[],int N)
{
int *temp=(int *)malloc(sizeof(int)*N);
Merge(array,temp,0,N-1);
//memcpy(array,temp,N);
return;
}
待排序的元素是个大的结构体,排序的过程中不需要移动原始数据本身,需要移动原始数据的指针。定义一个指针数组作为“表”,也称为间接排序。
桶排序
输入规模远大于规模的取值范围。如:4w个学生的成绩(0-100)
基数排序
输入规模远小于规模的取值范围。如将0-1000内的4个数据进行排序。