Sorting is one of the most basic functions applied to data. It means arranging the data in a particular fashion, which can be increasing or decreasing. There is a built-in function in C++ STL by the name of sort().
std::sort() is a generic function in C++ Standard Library, for doing comparison sorting.
sort(startaddress, endaddress, comparator) where: startaddress: the address of the first element of the array endaddress: the address of the last element of the array comparator: the comparison to be done with the array. This argument is optional.
Array after sorting using default sort is : 0 1 2 3 4 5 6 7 8 9
- Best Case – O(N log N)
- Average Case- O(N log N)
- Worse Case- O(N log N)
where, N = number of elements to be sorted.
Algorithms used by sort()
The algorithm used by sort() is IntroSort. Introsort being a hybrid sorting algorithm uses three sorting algorithm to minimise the running time, Quicksort, Heapsort and Insertion Sort. Simply putting, it is the best sorting algorithm around. It is a hybrid sorting algorithm, which means that it uses more than one sorting algorithms as a routine.
-313 -9 -9 1 3 23 23 32 233
Standard C library provides qsort() that can be used for sorting an array. As the name suggests, the function uses QuickSort algorithm to sort the given array
It is better to use sort() instead of qsort() because:
- sort() does not use unsafe void pointers like qsort().
- qsort() makes large number of function calls for comparison function compared to sort().
- C++ code with sort() is relatively faster than code with qsort().
Detailed article : Comparison of sort() with qsort()
- TCS Ninja Interview Experience (CSE) 2018 (In-Details)
- Print k different sorted permutations of a given array
- Merge K sorted arrays of different sizes | ( Divide and Conquer Approach )
- Generate a random permutation of elements from range [L, R] (Divide and Conquer)
- Minimize the sum of the squares of the sum of elements of each group the array is divided into
- Merge K sorted arrays | Set 3 ( Using Divide and Conquer Approach )
- Shortest path to traverse all the elements of a circular array in increasing order
- Use of Callbacks in Layered Architecture
- Passing and Returning Objects in C++
- Computer Graphics | Antialiasing
- Ethical Hacking | Footprinting
- Train a Support Vector Machine to recognize facial features in C++
- Make palindromic string non-palindromic by rearranging its letters
- Puzzle | Eliminating Virus from a Computer Network