×

C++ STL Tutorial

C++ STL Algorithm

C++ STL Arrays

C++ STL String

C++ STL List

C++ STL Stack

C++ STL Set

C++ STL Queue

C++ STL Vector

C++ STL Map

C++ STL Multimap

C++ STL MISC.

Sort an array in ascending order using sort() function in C++ STL

C++ STL - sort() function Example: In this article, we are going to learn how to sort array elements in Ascending Order using sort() function of C++ - STL?
Submitted by IncludeHelp, on January 03, 2018

Problem statement

Given an array and we have to sort the elements in Ascending Order using C++ STL sort() function.

How to Sort an Array in Ascending order using STL in C++?

To sort an array in ascending order using STL in C++, use the sort() function.

It is a built-in function of algorithm header file it is used to sort the containers like array, vectors in specified order.

Reference: http://www.cplusplus.com/reference/algorithm/sort/

Syntax

sort(first, last);

Parameter(s)

  • first - is the index (pointer) of first element from where we want to sort the elements.
  • last - is the last index (pointer) of last element.

For example, we want to sort elements of an array ‘arr’ from 1 to 5 position, we will use sort(arr, arr+5) and it will sort 5 elements in Ascending order.

Sample Input and Output

Input:
Array: 10, 1, 20, 2, 30

Output:
Sorted Array: 1, 2, 10, 20, 30

C++ program to sort an array in ascending order

#include <algorithm>
#include <iostream>
using namespace std;

int main() {
  // declare and define an array
  int arr[] = {10, 1, 20, 2, 30};

  // size of the array
  // total size/size of an element
  int size = sizeof(arr) / sizeof(int);

  // calling sort() to sort array elements
  sort(arr, arr + 5);

  // printing sorted elements
  cout << "Sorted elements are: ";
  for (int i = 0; i < size; i++) cout << arr[i] << " ";

  return 0;
}

Output

Sorted elements are: 1 2 10 20 30 

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.