×

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.

C++ STL sort function to sort an array or vector

In this article we are going to learn how we can use STL sort function to sort array or vector in C++?
Submitted by Radib Kar, on December 02, 2018

STL sort function

C++ STL has a default sort function which sort an array or vector in increasing order. Normally it uses quick sort which has a worst case time complexity of O(n^2) and average of O(nlogn).

To sort an array

Let the array be a[n] that mean the length of the array is n. To sort the array we need to write sort(a,a+n);

To sort a vector

vector<int> a; //a vector of integer type

To sort the vector in increasing order we need to write

sort(a.begin(),a.end());

C++ implementation of sort function to sort an array or vector

#include <bits/stdc++.h>
using namespace std;

int main() {
  // sorting an array
  cout << "............sorting an array............" << endl;
  // array defined
  int arr[10] = {34, 67, 54, 2, 4, 78, 63, 90, 12, 26};

  cout << "before sorting......." << endl;
  for (int i = 0; i < 10; i++) cout << arr[i] << " ";
  cout << endl;

  cout << "after sorting.........." << endl;
  sort(arr, arr + 10);  // using STL sort function
  for (int i = 0; i < 10; i++) cout << arr[i] << " ";
  cout << endl;

  // sorting a vector
  cout << "............sorting a vector............" << endl;
  vector<int> a;
  a.push_back(6);
  a.push_back(5);
  a.push_back(12);
  a.push_back(25);
  a.push_back(1);
  a.push_back(87);
  a.push_back(34);
  a.push_back(16);
  cout << "before sorting......." << endl;

  for (auto it = a.begin(); it != a.end(); it++) {
    cout << *it << " ";
  }
  cout << endl;

  sort(a.begin(), a.end());  // using STL sort function
  cout << "after sorting......." << endl;

  for (auto it = a.begin(); it != a.end(); it++) {
    cout << *it << " ";
  }
  cout << endl;

  return 0;
}

Output

............sorting an array............
before sorting.......
34 67 54 2 4 78 63 90 12 26
after sorting..........
2 4 12 26 34 54 63 67 78 90
............sorting a vector............
before sorting.......
6 5 12 25 1 87 34 16
after sorting.......
1 5 6 12 16 25 34 87

Comments and Discussions!

Load comments ↻





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