冒泡排序
#include<stdio.h>
#define N 10
void main(){
int a[N]={0};
int n,i,j,k,temp;
printf("The number is:\n");
scanf("%d",&n);
printf("Please input %d numbers:\n");
for(i=0;i<n&&i<N;i++){
scanf("%d",&a[i]);
}
//冒泡排序
for(j=0;j<n;j++){
for(k=0;k<n-1-j;k++){
if(a[k]<a[k+1]){
temp=a[k];
a[k]=a[k+1];
a[k+1]=temp;
}
}
}
//输出
for(i=0;i<n;i++){
printf("%4d",a[i]);
}
}
选择排序
下面展示一些 内联代码片
。
#include<stdio.h>
#define N 10
void main(){
int a[N]={0};
int n,i,j,k,min,temp;
printf("The number is:\n");
scanf("%d",&n);
printf("Please input %d numbers:\n",n);
for(i=0;i<n&&i<N;i++){
scanf("%d",&a[i]);
}
//选择排序
for(j=0;j<n-1;j++){
min=j;
for(k=j+1;j<n;j++){
if(a[k]<a[min]){
min=k; //记录交换的元素下标
}
}
if(j!=min){
temp=a[j];
a[j]=a[min];
a[min]=temp;
}
}
//输出
for(i=0;i<n;i++){
printf("%4d",a[i]);
}
}
快速排序
下面展示 代码
。
//快速排序,基于分治的思想
#include<stdio.h>
#define N 10
//交换两个数的值
void swap(int a[],int low,int high){
int temp;
temp=a[low];
a[low]=a[high];
a[high]=temp;
}
//计算基准点,分割为左右两个part
int partition(int a[],int low,int high){
int point=a[low];//选取第一个元素为基准点
while(low<high&&a[high]>point){
high--; //如果a[high]大于基准,那么high左移
}
while(low<high&&a[low]<point){
low--; //如果a[low]小于基准,那么low右移
}
swap(a,low,high);
}
void quicksort(int a[],int low,int high){
if(low<high){
int point=partition(a,low,high);//计算基准点
quicksort(a,low,point-1);//对左半部分进行排序
quicksort(a,point+1,high);//对右半部分进行排
}
}
void main(){
int a[N]={0};
int n,i,j,k,min,temp;
printf("The number is:\n");
scanf("%d",&n);
printf("Please input %d numbers:\n",n);
for(i=0;i<n&&i<N;i++){
scanf("%d",&a[i]);
}
quicksort(a,0,n-1);
for(i=0;i<n;i++){
printf("%4d",a[i]);
}
printf("\n");
}
插入排序
#include<stdio.h>
#define N 10
void insertsort(int a[],int n){
int i,j,temp;
for(i=1;i<n;i++){
temp=a[i];
j=i-1;
while(j>=0&&a[j]>temp){
a[j+1]=a[j];
j--;
}
a[j+1]=temp;
}
}
int main(){
int a[N]={0};
int i,j,n;
printf("The number is:\n");
scanf("%d",&n);
printf("Please input %d numbers:\n",n);
for(i=0;i<n&&i<N;i++){
scanf("%d",&a[i]);
}
insertsort(a,n);
for(i=0;i<n;i++){
printf("%4d",a[i]);
}
printf("\n");
}
希尔排序
#include <stdio.h>
#define N 10
void xiersort(int p[],int n)
{
int step = 0;//步长
int temp = 0;//用来保存第二段数据
int i,j;
for(step = n / 2;step > 0;step /= 2)
{
for(i = step;i < n;i++)
{
temp = p[i];
for(j = i - step;j >= 0 && p[j] > temp;j -= step)
{
p[j + step] = p[j];
//当满足条件时第一次j+step = i;后面的j+step = 上一次j的值
}
p[j + step] = temp;
}
}
}
void main()
{
int a[N]={0};
int i,j,n;
printf("The number is:\n");
scanf("%d",&n);
printf("Please input %d numbers:\n",n);
for(i=0;i<n&&i<N;i++){
scanf("%d",&a[i]);
}
xiersort(a,n);
for(i=0;i<n;i++){
printf("%4d",a[i]);
}
printf("\n");
}