STL归并排序

6 篇文章 0 订阅
#include<iostream>
#include<string.h>
#include<stdio.h>
#include<ctype.h>
#include<algorithm>
#include<stack>
#include<queue>
#include<set>
#include<math.h>
#include<vector>
#include<map>
#include<deque>
#include<list>
using namespace std;
int main()
{
    int n;
    int a[99999];
    while(scanf("%d",&n)!=EOF)
    {
        for(int i=0; i<n; i++)
            scanf("%d",&a[i]);
        nth_element(a,a+0,a+n);
        for(int i=0; i<n; i++)
            printf("%d ",a[i]);
        cout<<endl;
    }
    return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
C++ STL中的list容器提供了sort()函数,可以对链表进行排序。但是,由于链表的特殊性质,它不能像数组那样直接进行随机访问,因此在排序时需要使用归并排序算法。 具体实现方法如下: 1. 定义一个merge()函数,用于将两个有序链表合并成一个有序链表。 2. 定义一个mergeSort()函数,用于对链表进行归并排序。在该函数中,先将链表分成两个子链表,然后递归地对子链表进行排序,最后将两个有序子链表合并成一个有序链表。 3. 调用mergeSort()函数对整个链表进行排序。 以下是代码示例: ```c++ #include <iostream> #include <list> using namespace std; // 将两个有序链表合并成一个有序链表 void merge(list<int>& l1, list<int>& l2, list<int>& result) { auto it1 = l1.begin(); auto it2 = l2.begin(); while (it1 != l1.end() && it2 != l2.end()) { if (*it1 < *it2) { result.push_back(*it1); ++it1; } else { result.push_back(*it2); ++it2; } } while (it1 != l1.end()) { result.push_back(*it1); ++it1; } while (it2 != l2.end()) { result.push_back(*it2); ++it2; } } // 对链表进行归并排序 void mergeSort(list<int>& l) { if (l.size() <= 1) { return; } list<int> l1, l2; auto it = l.begin(); for (int i = 0; i < l.size() / 2; ++i) { l1.push_back(*it); ++it; } for (; it != l.end(); ++it) { l2.push_back(*it); } mergeSort(l1); mergeSort(l2); l.clear(); merge(l1, l2, l); } int main() { list<int> l = {3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5}; mergeSort(l); for (auto x : l) { cout << x << " "; } cout << endl; return 0; } ```

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值