归并排序
#include<stdio.h>
int a[10000],a2[10000];
void Merge(int sta,int mid,int end){
int k=0;
int i;
i=sta;
int j;
j=mid+1;
while(i<=mid&&j<=end){
if(a[i]<a[j]){
a2[k++]=a[i++];
}
else{
a2[k++]=a[j++];
}
}
while(i<=mid){
a2[k++]=a[i++];
}
while(j<=end){
a2[k++]=a[j++];
}
for(i=sta,j=0;j<k;i++,j++){
a[i]=a2[j];
}
}
void Mergesort(int sta,int end){
if(sta==end){
return ;
}
else
{
int mid=(sta+end)/2;
Mergesort(sta,mid);
Mergesort(mid+1,end);
Merge(sta,mid,end);
}
}
int main()
{
int total;
scanf("%d",&total);
for(int i=0;i<total;i++){
scanf("%d",&a[i]);
}
Mergesort(0,total-1);
for(int i=0;i<total;i++){
printf("%d ",a[i]);
}
return 0;
}
快速排序
#include<stdio.h>
int a[10000];
int Parition(int low,int high){
int pivot=a[low];
while(low<high){
while(low<high&&a[high]>=pivot){
high--;
}
a[low]=a[high];
while(low<high&&a[low]<=pivot){
low++;
}
a[high]=a[low];
}
a[low]=pivot;
return low;
}
void Quicksort(int low,int high)
{
if(low<high){
int pivot=Parition(low,high);
Quicksort(low,pivot);
Quicksort(pivot+1,high);
}
}
int main()
{
int total;
scanf("%d",&total);
for(int i=0;i<total;i++){
scanf("%d",&a[i]);
}
Quicksort(0,total-1);
for(int i=0;i<total;i++){
printf("%d ",a[i]);
}
return 0;
}
排序函数sort
#include<iostream>
#include<algorithm>
#include<stdio.h>
using namespace std;
int a[10000];
int comp(int a,int b){
return a>b;
}
int main()
{
int total;cin>>total;
for(int i=0;i<total;i++){
cin>>a[i];
}
sort(a,a+total);
for(int i=0;i<total;i++){
printf("%d ",a[i]);
}
printf("\n");
sort(a,a+total,comp);
for(int i=0;i<total;i++){
printf("%d ",a[i]);
}
return 0;
}