几个基本排序算法的代码实现(C语言)
2016-02-14 16:40
981 查看
首先,是冒泡排序自顶向下方法
其次,插入排序
最后一个是快速排序
#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;
}
几种常见的排序方法就练习到这了
#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;
}
几种常见的排序方法就练习到这了
相关文章推荐
- 使用 C++ bitset 操纵浮点数类型(float、double)
- C语言之指针复习
- c++中冒号(:)和双冒号(::)的区别
- c语言 float 保留小数点后两位数字
- C/C++中的getline函数总结
- c++ getline()函数
- leetcode83题 题解 翻译 C语言版 Python版
- 如何用 OS X 的 Xcode 写C语言程序
- mc++ gdi+ 绘图功能
- C++程序设计之类的属性
- C++运算符重载函数作为类成员函数和友元函数
- 机器学习 深度学习 C/C++学习资料汇总链接
- 算法训练 输出米字形
- C++运算符重载
- 用C++访问SQL Server数据库
- c++模板的特化
- C++ 学习(第一天)C++中调用C编译器的函数的原理
- C++ 学习(第一天)sizeof与strlen 的区别
- C语言递归操作用法总结
- VC++使用ADO连接SQL Server数据库