Nous avons discuté qsort() en C. C++ STL fournit une fonction de tri similaire qui trie un vecteur ou un tableau (éléments à accès aléatoire)
Cela prend généralement deux paramètres, le premier étant le point du tableau/vecteur à partir duquel le tri doit commencer et le deuxième paramètre étant la longueur jusqu'à laquelle nous voulons que le tableau/vecteur soit trié. Le troisième paramètre est facultatif et peut être utilisé dans des cas comme si l'on souhaite trier les éléments lexicographiquement.
Par défaut, la fonction sort() trie les éléments par ordre croissant.
Vous trouverez ci-dessous un programme simple pour montrer le fonctionnement de sort().
RPC
// 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; }> |
>
>Sortir
Array after sorting using default sort is : 0 1 2 3 4 5 6 7 8 9>
Complexité temporelle : O(N log N)
Espace auxiliaire : O(1)
Comment trier par ordre décroissant ?
sort() prend un troisième paramètre utilisé pour spécifier l'ordre dans lequel les éléments doivent être triés. Nous pouvons passer la fonction Greater() pour trier par ordre décroissant. Cette fonction effectue une comparaison de manière à placer les éléments les plus importants avant.
RPC
// 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; }> |
>
>Sortir
Array after sorting : 9 8 7 6 5 4 3 2 1 0>
Complexité temporelle : O(N log N)
Espace auxiliaire : O(1)
Triez le tableau uniquement dans la plage donnée : Pour faire face à de tels types de problèmes, il suffit de mentionner la plage à l'intérieur de la fonction de tri.
Vous trouverez ci-dessous la mise en œuvre du cas ci-dessus :
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> |
>
>Sortir
Array after sorting : 0 1 2 3 4 5 6 7 8 9>
Complexité temporelle : O (N log N)
Espace auxiliaire : O(1)
Comment trier dans un ordre particulier?
Nous pouvons également écrire notre propre fonction de comparaison et la transmettre comme troisième paramètre. Cette fonction de comparaison renvoie une valeur ; convertible en bool, qui nous indique essentiellement si le premier argument passé doit être placé avant le deuxième argument passé ou non.
Par exemple : dans le code ci-dessous, supposons que les intervalles {6,8} et {1,9} soient passés comme arguments dans la fonction compareInterval (fonction de comparaison). Maintenant comme i1.first (=6)
RPC
// 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; }> |
>
>Sortir
Intervals sorted by start time : [1,9] [2,4] [4,7] [6,8]>
La complexité temporelle de std::sort() est:
vues et tableaux
- Meilleur cas – O (N log N)
- Cas moyen – O (N log N)
- Pire des cas – O (N log N)
Complexité spatiale : Il peut utiliser l'espace auxiliaire 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 |
>
>Sortir
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>
Complexité temporelle : O(N log N)
Espace auxiliaire : O(1)