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()
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.
In case you wish to attend live classes with industry experts, please refer DSA Live Classes