下面我写了几种排序,还不全,有一些是学习其他博客的。大神那么多,奋起直追吧。还有就是不断的进行复习,熟练的掌握知识。
1 .c++排序调用
#include<algorithm> bool cmp(int a,int b){ return a>b; } sort(a,n)//从小到大排序 sort(a,n,cmp)//从到到小排序
2.快速排序
int partition(int *l,int low,int high) {
int temp=l[low];
while (low <high) {
while (low<high&&l[high] >= temp) {
high--;
}
l[low] = l[high];
while (low<high&&l[low] <= temp) {
low++;
}
l[high] = l[low];
}
l[low] = temp;
return low;
}
void quicksort(int *l, int low, int high) {
int p;
if(low<high){
p = partition(l,low,high);
quicksort(l, low, p - 1);
quicksort(l, p + 1, high);
}
}
3.归并排序
#define INF 0x3f3f3f3f
void merge(int a[],int l,int mid,int r){
int size1=mid-l+1;
int size2=r-mid;
int L[size1+1],R[size2+1];
for(int i=0;i<size1;i++)
{ L[i]=a[l+i];}
for(int i=0;i<size2;i++)
{ R[i]=a[1+mid+i];}
L[size1]=INF;
R[size2]=INF;
int left=0,right=0;
for(int k=l;k<=r;k++){
if(L[left]<=R[right]){
a[k]=L[left];
left++;
}else{
a[k]=R[right];
right++;
}
}
}
void mergesort(int a[],int l,int r){
if(l<r){
int mid=(l+r)/2;
mergesort(a,l,mid);
mergesort(a,mid+1,r);
merge(a,l,mid,r);
}
}
4.插入排序
void insertsort(int a[],int size){
for(int i=1;i<size;i++){
int temp=a[i];
int j=i-1;
while(j>=0&&temp<a[j]){
a[j+1]=a[j];
j--;
}
a[j+1]=temp;
}
}
5. 冒泡排序
void bubblesort(int a[],int size){
int temp;
for(int i=0;i<size;i++){
for(int j=0;j<size-i-1;j++){
if(a[j]>a[j+1]){
temp=a[j];
a[j]=a[j+1];
a[j+1]=temp;
}
}
}
}
6.选择排序
void selectsort(int a[],int size){
for(int i=0;i<size-1;i++){
int minindex=i;
for(int j=i+1;j<size-1;j++){
if(a[j]<a[minindex]){
minindex=j;
}
}
if(a[i]>a[minindex]){
int temp=a[i];
a[i]=a[minindex];
a[minindex]=a[i];
}
}
}