解题思路:
因为数据范围大,不能使用时间复杂度为O(n2)的,因此使用O(nlogn)的快速排序或直接用sort()函数。
题解:
解法一:sort()函数
#include <bits/stdc++.h>
using namespace std;
const int N = 1e5 + 9;//有可能会出现超过的情况,所以加几个
int a[N];
int main()
{
ios::sync_with_stdio(0), cin.tie(0), cout.tie(0);
int n;cin >> n;
for(int i = 0; i < n; i++)
{
cin >> a[i];
}
sort(a, a + n);//必须是起始位置,和最后一个元素的下一位,否则会出现数据对不上的情况
for(int i = 0; i < n; i++)
{
cout << a[i] << " \n"[i == (n - 1)];
//为了达到题目的输出效果,后面这段" \n"[i == (n -=- 1)]必须加
}
return 0;
}
解法二:快速排序
#include <bits/stdc++.h>
using namespace std;
const int N = 1e5 + 9;
int a[N];
int partition(int a[], int l, int r) // 注意区分l和1
{
int pivot = a[r], i = l, j =r;
while(i < j)
{
while(i < j && a[i] <= pivot)i++;
while(i < j && a[j] >= pivot)j--;
if(i < j)swap(a[i], a[j]);
else swap(a[i], a[r]);
}
return i;
}
void QuickSort(int a[], int l, int r)
{
if(l < r)
{
int mid = partition(a, l, r);
QuickSort(a, l, mid - 1);
QuickSort(a, mid + 1, r);
}
}
int main()
{
ios::sync_with_stdio(0), cin.tie(0), cout.tie(0);
int n;cin >> n;
for(int i = 1; i <= n; i++)cin >> a[i];
QuickSort(a, 1, n);
for(int i = 1; i <= n; i++)cout << a[i] << " \n"[i == n];
return 0;
}
知识点:sort()、快速排序