Sort
Sort
Sort
Let m0, m1, …, mn-1 are n integers in array m (int m[1001]) to be sorted. You can use
STL function sort:
sort(m, m + n);
Here
• m = &m[0] is a pointer to the first element;
• m + n = &m[n] is a pointer to the elment that is next to the last element;
0 1 2 3 4 5
6 2 8 9 12 1
n = 6 elements
m m+n
If you have a vector (vector<int> v), use the next format:
sort(v.begin(), v.end());
0 1 2 3 4 5
6 2 8 9 12 1
v.begin() v.end()
In this problem you can use swap sort with complexity O(n2). Since n ≤ 1000, this
algorithm will pass the time limit. Iterate over all pairs (i, j), 0 ≤ i < j < n, and if m[i] >
m[j], swap them.
1 8 4 6 2 9 swap(m[i],m[j]) 1 2 4 6 8 9
i j i j
#include <stdio.h>
#define MAX 1010
int m[MAX];
int i, n;
void sort(void)
{
int i, j, temp;
for (i = 0; i < n; i++)
for (j = i + 1; j < n; j++)
if (m[i] > m[j])
{
temp = m[i]; m[i] = m[j]; m[j] = temp;
}
}
int main(void)
{
scanf("%d", &n);
for (i = 0; i < n; i++)
scanf("%d", &m[i]);
sort();
To sort the data in increasing or decreasing order you can use comparators:
• sort(m, m + n, less<int>()) – sort in increasing order;
• sort(m, m + n, greater<int>()) – sort in decreasing order;
To sort the vector v, use
• sort(v.begin(), v.end(), less<int>()) – sort in increasing order;
• sort(v.begin(), v.end(), greater<int>()) – sort in decreasing order;
To sort the data in increasing order, you can omit the comparator. Default order is
increasing.
You can write your own comparator. Comparator is a function of the form
int f(type a, type b)
{
. . .
}
that returns true (1), if elements a and b should not be swapped and false (0)
otherwise. Consider array m and two elements: a = m[i], b = m[j], where i < j. If m[i]
and m[j] must be swapped to preserve the sorting order, then comparator must return
false.
i j
a b
f(a, b)
true false
i j i j
a b b a
For sorted array the value of the function f(a, b) must be true for any elements a
and b such that position of a is less than the position of b. The next comparator sorts
array of integers in decreasing order:
12 9 7 7 7 5 2
a > b
int m[MAX];
int i, n;
sort(m, m + n, f);
E-OLYMP 4848. Quick sort Sort the given sequence in non-decreasing order.
► Read the sequence of numbers into array till the end of file and use any sorting
algorithm.
int main(void)
{
cin >> s;
sort(s.begin(),s.end(),less<int>());
cout << s << "\n";
sort(s.begin(),s.end(),greater<int>());
cout << s << "\n";
return 0;
}