0

This code is about sorting an array :

#include <bits/stdc++.h>
using namespace std;
 
int main()
{
    int arr[] = { 1, 5, 8, 9, 6, 7, 3, 4, 2, 0 };
    int n = sizeof(arr) / sizeof(arr[0]);
    sort(arr, arr + n);   

    cout << "\nArray after sorting using "
        "default sort is : \n"; 

    //Here I started printing the array
    for (int i = 0; i < n; ++i)
        cout << arr[i] << " ";

    return 0;
}     

Unfortunately, I am unable to understand this line :

 sort(arr, arr + n);  

How arr+n specifies end position here ?

3 Answers3

1

For arrays, array name arr indicates iterator pointing to first element of array and +n would increment that iterator by n elements. In your case, the sort algorithm should take beginning iterator and iterator pointing to one beyond last element.

arr: beginning iterator arr+n: ending iterator (one beyond last element)

Typically, algorithms don't count ending iterator in their range, so it's like this.

Asphodel
  • 180
  • 1
  • 1
  • 11
0

The convention on the standard libraries is that the ranges must be provided as an iterator pointing to the first element and an iterator pointing to one past the last element.

So your sequence has 10 elements

 array = { 1, 5, 8, 9, 6, 7, 3, 4, 2, 0 };
 index =>  0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 

so arr[0] points to the first element and arr[10] points to one past the last element.

0

The code snippet sort(arr, arr + n); is an invocation of the sort() function in C++ to sort an array. It is assuming that arr is a pointer to the beginning of the array, and n is the number of elements in the array. The sort() function is part of the C++ Standard Template Library (STL) and is used to sort elements in ascending order by default.

Here's a breakdown of the function call:

arr: This is the pointer to the first element of the array. In C++, when you pass an array to a function, it decays to a pointer to its first element, so in most cases, you can treat an array as a pointer.

arr + n: This is the pointer to the element one past the last element of the array. It helps define the range of elements that should be sorted. The sort() function uses a half-open range, where the first iterator is inclusive, and the last iterator is exclusive. In this case, arr + n points to the position after the last element of the array.

sort(): This is the function from the C++ Standard Template Library (STL) used for sorting the elements within the specified range.

The sort function will reorder the elements in the array pointed to by arr, arranging them in ascending order based on their values. After the function call, the array will contain its elements in sorted order.

Here's an example of how you might use the sort() function: