- 冒泡排序:
#include <stdio.h>
int main(){
int a[5] = {1,5,8,3,0};
int i,j,l,temp;
for(i=1;i<5;i++)
for(j=0;j<5-i;j++)
if(a[j] >= a[j+1]){
temp = a[j];
a[j] = a[j+1];
a[j+1] = temp;
}
for(i=0;i<5;i++)
printf("%d",a[i]);
return 0;
}
2.选择排序
#include <stdio.h>
int main(){
int a[5] = {1,5,8,3,0};
int temp,min,count,n=5;
for(int i=0;i<n;i++){
min = a[i];
count = i;
for(int j=i;j<n;j++){
if(a[j]<min){
min = a[j];
count = j;
}
}
temp = a[i];
a[i] = a[count];
a[count] = temp;
}
for(int i=0;i<n;i++)
printf("%d ",a[i]);
return 0;
}
- 插入排序
#include <stdio.h>
int main(){
int a[5] = {1,5,8,3,0};
int temp,n = 5;
for(int i=1;i<n;i++){
temp = a[i];
while(a[i-1]>temp){
a[i] = a[i-1];
i--;
}
a[i] = temp;
}
for(int i=0;i<n;i++){
printf("%d ",a[i]);
}
return 0;
}
- 快速排序
#include <stdio.h>
int Partition(int a[],int left,int right){
int temp = a[left];
while(left<right){
while(left<right&&a[right]>temp)right--;
a[left] = a[right];
while(left<right&&a[left]<=temp)left++; // 注意这里是小于等于号
a[right] = a[left];
}
a[left] = temp;
return left; // 返回相遇的下标
}
void quicksort(int a[],int left,int right){
if(left<right){
int pos = Partition(a,left,right);
quicksort(a,left,pos-1);
quicksort(a,pos+1,right);
}
}
int main(){
int a[]={1,3,2,5,2,4,5,6};
quicksort(a,0,7);
for(int i=0;i<8;i++){
printf("%d ",a[i]);
}
return 0;
}
- 二路归并排序
#include <stdio.h>
const int max=100;
void merge(int a[],int L1,int R1,int L2,int R2){
int temp[max];
int i=0;
int k=L1;
while(L1<=R1&&L2<=R2){ // 注意有等号
if(a[L1]<a[L2]){
temp[i++]=a[L1++];
}else{
temp[i++]=a[L2++];
}
}
while(L1<=R1){ // 注意有等号
temp[i++] = a[L1++];
}
while(L2<=R2){ // 注意有等号
temp[i++] = a[L2++];
}
for(int j=0;j<i;j++){
a[k+j] = temp[j];
}
}
void mergeSort(int a[],int left,int right){
if(left<right){
int mid=(left+right)/2;
mergeSort(a,left,mid);
mergeSort(a,mid+1,right);
merge(a,left,mid,mid+1,right);
}
}
int main(int argc,char **argv){
int a[]={1,3,2,5,2,4,5,6};
mergeSort(a,0,7);
for(int i=0;i<8;i++){
printf("%d ",a[i]);
}
return 0;
}