std::sort() w C++ STL

Omówiliśmy qsort() w C. C++ STL udostępnia podobną funkcję sortowania, która sortuje wektor lub tablicę (elementy o dostępie swobodnym)

Zwykle przyjmuje dwa parametry, pierwszy to punkt tablicy/wektora, od którego należy rozpocząć sortowanie, a drugi to długość, do której tablica/wektor ma zostać posortowana. Trzeci parametr jest opcjonalny i można go zastosować np. gdy chcemy posortować elementy leksykograficznie.

Domyślnie funkcja sort() sortuje elementy w kolejności rosnącej.

Poniżej znajduje się prosty program pokazujący działanie sort().

CPP




// C++ program to demonstrate default behaviour of> // sort() in STL.> #include> using> namespace> std;> int> main()> {> > int> arr[] = { 1, 5, 8, 9, 6, 7, 3, 4, 2, 0 };> > int> n => sizeof> (arr) /> sizeof> (arr[0]);> > /*Here we take two parameters, the beginning of the> > array and the length n upto which we want the array to> > be sorted*/> > sort(arr, arr + n);> > cout < <> ' Array after sorting using '> > 'default sort is : '> ;> > for> (> int> i = 0; i cout < < arr[i] < < ' '; return 0; }>

Wyjście

Array after sorting using default sort is : 0 1 2 3 4 5 6 7 8 9 

Złożoność czasowa: O(N log N)
Przestrzeń pomocnicza: O(1)

Jak sortować w kolejności malejącej?
sort() przyjmuje trzeci parametr używany do określenia kolejności sortowania elementów. Możemy przekazać funkcję większe(), aby posortować w porządku malejącym. Ta funkcja dokonuje porównania w sposób, który stawia większe elementy na pierwszym miejscu.

CPP




// C++ program to demonstrate descending order sort using> // greater().> #include> 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, greater <> int> >());> > cout < <> 'Array after sorting : '> ;> > for> (> int> i = 0; i cout < < arr[i] < < ' '; return 0; }>

Wyjście

Array after sorting : 9 8 7 6 5 4 3 2 1 0 

Złożoność czasowa: O(N log N)
Przestrzeń pomocnicza: O(1)

Sortuj tablicę tylko w podanym zakresie: Aby poradzić sobie z tego typu problemami, wystarczy wspomnieć o zakresie wewnątrz funkcji sortowania.
Poniżej implementacja powyższego przypadku:

C++




// C++ program to demonstrate sort()> #include> using> namespace> std;> int> main()> {> > int> arr[] = { 0, 1, 5, 8, 9, 6, 7, 3, 4, 2 };> > int> n => sizeof> (arr) /> sizeof> (arr[0]);> > // Sort the elements which lies in the range of 2 to> > // (n-1)> > sort(arr + 2, arr + n);> > cout < <> 'Array after sorting : '> ;> > for> (> int> i = 0; i cout < < arr[i] < < ' '; return 0; } // This code is contributed by Suruchi Kumari>

Wyjście

Array after sorting : 0 1 2 3 4 5 6 7 8 9 

Złożoność czasowa: O(N log N)

Przestrzeń pomocnicza: O(1)

Jak sortować w konkretna kolejność?
Możemy także napisać własną funkcję komparatora i przekazać ją jako trzeci parametr. Ta funkcja komparatora zwraca wartość; konwertowalny na bool, który zasadniczo mówi nam, czy przekazany pierwszy argument powinien zostać umieszczony przed przekazanym drugim argumentem, czy nie.
Na przykład: W poniższym kodzie załóżmy, że przedziały {6,8} i {1,9} są przekazywane jako argumenty w funkcji CompareInterval (funkcja komparatora). Teraz jako i1.first (=6)

CPP




// A C++ program to demonstrate> // STL sort() using> // our own comparator> #include> using> namespace> std;> // An interval has a start> // time and end time> struct> Interval {> > int> start, end;> };> // Compares two intervals> // according to starting times.> bool> compareInterval(Interval i1, Interval i2)> {> > return> (i1.start } int main() { Interval arr[] = { { 6, 8 }, { 1, 9 }, { 2, 4 }, { 4, 7 } }; int n = sizeof(arr) / sizeof(arr[0]); // sort the intervals in increasing order of // start time sort(arr, arr + n, compareInterval); cout < < 'Intervals sorted by start time : '; for (int i = 0; i cout < < '[' < < arr[i].start < < ',' < < arr[i].end < < '] '; return 0; }>

Wyjście

Intervals sorted by start time : [1,9] [2,4] [4,7] [6,8] 

Złożoność czasowa std::sort() Jest:

  1. Najlepszy przypadek – O(N log N)
  2. Przypadek przeciętny – O(N log N)
  3. Najgorszy przypadek – O(N log N)

Złożoność przestrzeni: Może używać przestrzeni pomocniczej O(log N).

C++




#include> #include> using> namespace> std;> template> <> class> T>> class> Comparator {> // we pass an object of this class as> > // third arg to sort function...> public> :> > bool> operator()(T x1, T x2)> > {> > return> x1 } }; template bool funComparator(T x1, T x2) { // typem powrotu jest bool return x1 <= x2; } void show(int a[], int array_size) { for (int i = 0; i cout < < a[i] < < ' '; } } int main() { int a[] = { 1, 5, 8, 9, 6, 7, 3, 4, 2, 0 }; int asize = sizeof(a) / sizeof(int); cout < < 'The array before sorting is : '; show(a, asize); cout < < endl < < 'The array after sorting is(asc) :'; sort(a, a + asize); show(a, asize); cout < < endl < < 'The array after sorting is(desc) :'; sort(a, a + asize, greater ()); show(a, rozmiar); cout < < endl < < 'The array after sorting is(asc but our ' 'comparator class) :'; sort(a, a + asize, Comparator ()); show(a, rozmiar); cout < < endl < < 'The array after sorting is(asc but our ' 'comparator function) :'; sort(a, a + asize, funComparator ); show(a, rozmiar); zwróć 0; }>

Wyjście

The array before sorting is : 1 5 8 9 6 7 3 4 2 0 The array after sorting is(asc) :0 1 2 3 4 5 6 7 8 9 The array after sorting is(desc) :9 8 7 6 5 4 3 2 1 0 The array after sorting is(asc but our comparator class) :0 1 2 3 4 5 6 7 8 9 The array after sorting is(asc but our comparator function) :0 1 2 3 4 5 6 7 8 9 

Złożoność czasowa: O(N log N)
Przestrzeń pomocnicza: O(1)