c++笔记排序集合(模板)

冒泡:

//从大到小
#include<bits/stdc++.h>
using namespace std;
int main(){
	int a[11]={-1,3,2,1,4,6,7,5,8,9,10};
	for(int i=1;i<=10;i++)
		for(int j=1;j<10;j++)
			if(a[i]>a[j]) swap(a[i],a[j]);
	for(int i=1;i<=10;i++)
		cout<<a[i]<<" ";
	return 0;
}
//从小到大
#include<bits/stdc++.h>
using namespace std;
int main(){
	int a[11]={-1,3,2,1,4,6,7,5,8,9,10};
	for(int i=1;i<=10;i++)
		for(int j=1;j<10;j++)
			if(a[i]<a[j]) swap(a[i],a[j]);
	for(int i=1;i<=10;i++)
		cout<<a[i]<<" ";
	return 0;
}

选排:

//从小到大
#include<bits/stdc++.h>
using namespace std;
int main(){
	int a[11]={-1,1,9,2,3,8,5,4,7,10,6};
	for(int i=1;i<=10;i++){
		int minPosition=i;
		for(int j=i+1;j<=10;j++)
			if(a[j]<a[minPosition]) minPosition=j;
		swap(a[i],a[minPosition]);
	}
	for(int i=1;i<=10;i++)
		cout<<a[i]<<" ";
	return 0;
}

//从大到小
#include<bits/stdc++.h>
using namespace std;
int main(){
	int a[11]={-1,1,9,2,3,8,5,4,7,10,6};
	for(int i=1;i<=10;i++){
		int maxPosition=i;
		for(int j=i+1;j<=10;j++)
			if(a[j]>a[maxPosition]) maxPosition=j;
		swap(a[i],a[maxPosition]);
	}
	for(int i=1;i<=10;i++)
		cout<<a[i]<<" ";
	return 0;
}

插排

//从小到大
#include<bits/stdc++.h>
using namespace std;
int main(){
	int a[11]={-1,1,3,4,8,9,2,10,7,5,6};
	for(int i=1;i<=10;i++)
		for(int j=i;j>=1;j--)
			if(a[j]<a[j-1]) swap(a[j],a[j-1]);
	for(int i=1;i<=10;i++)
		cout<<a[i]<<" ";
	return 0;
}
//从大到小
#include<bits/stdc++.h>
using namespace std;
int main(){
	int a[11]={-1,1,3,4,8,9,2,10,7,5,6};
	for(int i=1;i<=10;i++)
		for(int j=i;j>=1;j--)
			if(a[j]>a[j-1]) swap(a[j],a[j-1]);
	for(int i=1;i<=10;i++)
		cout<<a[i]<<" ";
	return 0;
}

快排:

//从小到大
sort(a+1,a+1+n)
//从大到小
bool cmp(int u,int v){
    return a>b;
}
//主函数
sort(a+1,a+1+n,cmp);

归并排序:

#include <iostream>
 
void Merge(int r[], int r1[], int s, int m, int t)
{
    int i = s;
    int j = m + 1;
    int k = s;
    while (i <= m && j <= t)
    {
        if (r[i] <= r[j])
            r1[k++] = r[i++];
        else
            r1[k++] = r[j++];
    }
    if (i <= m)
        while (i <= m)
            r1[k++] = r[i++];
    else
        while (j <= t)
            r1[k++] = r[j++];
    for (int n = s; n <= t; n++)
        r[n] = r1[n];
}
 
void MergeSort(int r[], int r1[], int s, int t)
{
    if (s < t)
    {
        int m = (s + t) / 2;
        MergeSort(r, r1, s, m);
        MergeSort(r, r1, m + 1, t);
        Merge(r, r1, s, m, t);
    }
}
 
int main()
{
    int r[8] = {10, 3, 5, 1, 9, 34, 54, 565}, r1[8];
    MergeSort(r, r1, 0, 7);
    for (int q = 0; q < 8; q++)
        std::cout << r[q] << std::ends;
    return 0;
}
0 0 vote
Article Rating
Subscribe
提醒
4 评论
Newest
Oldest Most Voted
Inline Feedbacks
View all comments
Rolling_Code

建议添加猴排。

23786 蘑菇蘑菇蘑菇蘑
bool cmp(int u,int v){
    return a>b;
}

认真的?

Zhang, Xuheng

变量错了
!

4
0
Would love your thoughts, please comment.x
()
x