您的位置:首页 > 编程语言 > C语言/C++

几个基本排序算法的代码实现(C语言)

2016-02-14 16:40 981 查看
首先,是冒泡排序自顶向下方法
#include <stdio.h>
int main(void) {
int a[5],num=5,temp,j,pov=0,i=0;
for(i=0;i<5;i++)
scanf("%d",&a[i]);
while(num!=0){
//	pov=a[0];
for(j=0;j<num-1;j++)
{
if(a[j+1]<a[j]){
temp=a[j];
a[j]=a[j+1];
a[j+1]=temp;
pov=1;
}
}
if(pov==0)
break;
num--;
}
for(i=0;i<5;i++)
printf("%d ",a[i]);
return 0;
}

其次,插入排序

#include <stdio.h>
void insertsort(int a[],int nums){
int pov=0,i=1,key,n;
while(i!=nums)
{
key=a[i];
n=i;
while(a[pov]>key&&pov!=-1)
{
a
=a[pov];
n--;
pov--;
}
a
=key;
pov=i;
i++;
}
}
int main(void) {
int a[5],i=0;
for(i=0;i<5;i++)
scanf("%d",&a[i]);
insertsort(a,5);
for(i=0;i<5;i++)
printf("%d ",a[i]);
return 0;
}


最后一个是快速排序

#include <stdio.h>
int quick(int a[],int low,int high){
int pvot=a[low],temp;
while(low<high){
while(pvot<a[high]&&low<high)
high--;
temp=a[high];
a[high]=pvot;
a[low]=temp;
while(pvot>a[low]&&low<high)
low++;
temp=a[low];
a[low]=pvot;
a[high]=temp;
}
return low;
}
void quicksort(int a[],int low,int high){
int mid=quick(a,low,high);
if(mid>low)
quicksort(a,low,mid-1);
if(mid<high)
quicksort(a,mid+1,high);

}
int main(void) {
// your code goes here
int a[5],i=0;
for(i=0;i<5;i++)
scanf("%d",&a[i]);
quicksort(a,0,4);
for(i=0;i<5;i++)
printf("%d ",a[i]);
return 0;
}


几种常见的排序方法就练习到这了
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: