Sort sorting combat - cross sorting (it turns out that my understanding of sort was still wrong before)

cross sort

Mr. Garantou is bored, he wants to sort some elements in the array.

Now that we have N numbers, he wants to first sort the numbers from l1​ to r1​ in the array in ascending order. Then sort the numbers from l2​ to r2​ in the array in descending order.

Let's help him calculate the result of sorting the array~

input format

The first line contains five integers N,l1​,r1​,l2​,r2​, of which 0<l1​<r1​<N,0<l2​<r2​<N, these five numbers do not exceed 10000;

The second row is N integers.

Sample output

A line of N integers, representing the result of sorting the array, separated by spaces, and a new line at the end.

Sample input copy

6 1 3 2 4
8 3 1 6 9 2

Sample output copy

1 8 6 3 9 2

 


Code:

Misunderstanding:

At first I wrote the ordering of the range l1 to r1 as:

	sort(a + l1 + 1, a + r1 +1, less<int>());
	sort(a + l2 + 1, a + r2 +1, greater<int>());

Actually sort(a,a+n); //The two parameters are the first and last addresses of the array to be sorted

The range of the two parameters of sort is left closed and right open

for example:

l1 = 1, r1 = 2, that is to say, the first element and the second element are sorted, and the subscript starts from 1

We would write (sort(a + l1, a + r1 + 1);

This is left closed and right open, and the right is the last bit of the last element of the array, which is actually impossible to get.

That is to say, the effective subscript of the a array starts from 1, so the address of the starting element should be a + l1 instead of a + l1 + 1

 

#include<iostream>
#include<algorithm> 
using namespace std;
int n, l1, r1, l2, r2;
int a[10005];

int main(){
	ios::sync_with_stdio(false);
	cin >> n >> l1 >> r1 >> l2 >> r2;
	for(int i = 1; i <= n; i++){
		cin >> a[i];
	}
    //一定要注意左边端点是 a + l1 !!!!!!
    //不是 a + l1 + 1
	sort(a + l1 , a + r1 + 1, less<int>());
	sort(a + l2 , a + r2 + 1, greater<int>());
	for(int i = 1; i <= n; i++){
		if(i < n)
			cout << a[i] << " ";
		else
			cout << a[i] << endl;
	}
	return 0;
}

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326312986&siteId=291194637