Sorting and searching can be said is the most classic problem of the computer field,
and the C ++ standard library header files ** algorithm ** has been built based on the function sort quick sort, simply calling this function, you can easily complete the sort.
Sort functions are briefly described below: sort (first, last, comp) function takes three parameters:
The starting address to be sorted sequence: 1. first
end address to be sorted sequence (start address of the last element): 2. Last
3. CoMP: ordering, may not be filled, while ascending order by default does not fill
Example 1: Default ascending sort
#include <iostream> #include <algorithm> using namespace std; int main () { int arr[5] = {3, 6, 1, 4, 7}; cout << "排序前:"; for (int i = 0; i < 5; i++) { cout << arr[i] << ' '; } cout << endl; Sort (ARR, ARR + . 5 ); // Sort: Ascending default COUT << " sorted: " ; for ( int I = 0 ; I < . 5 ; I ++ ) { cout << arr[i] << ' '; } return 0; }
Output: Before sorting: . 3 . 6 . 1 . 4 . 7 sorted: . 1 . 3 . 4 . 6 . 7
Example 2: in descending order, you have written a Sort
#include <iostream> #include <algorithm> using namespace std; BOOL the Compare ( int X, int Y) // Sort Descending { return X> Y; } int main () { int arr[5] = {3, 6, 1, 4, 7}; cout << "排序前:"; for (int i = 0; i < 5; i++) { cout << arr[i] << ' '; } cout << endl; Sort (ARR, ARR + . 5 , the Compare); // Sort: using a descending sort mode COUT << " after sorting: " ; for ( int I = 0 ; I < . 5 ; I ++ ) { cout << arr[i] << ' '; } return 0; }
Output: : Before sorting . 3 . 6 . 1 . 4 . 7 sorted: . 7 . 6 . 4 . 3 . 1
Example 3: Sort by its own definition, can achieve many scenes sort of
example: sort of student achievement, sorted by highest to lowest, and student information printing. Information including school students, grades; if student achievement are the same, according to the size of the student number in ascending order.
#include <iostream> #include <algorithm> using namespace std; struct Student { int Number; // Student ID int Score; // score }; const int MAXN = 100 ; Student arr[MAXN]; BOOL the Compare (Student X, Y Student) { IF (x.score == y.score) { // the same results, a small number of learning front return x.number < y.number; } the else { return x.score> y.score; // a high score former } } int main () { int n; cin >> n; for (int i = 0; i < n; i++) { cin >> arr[i].number >> arr[i].score; } sort(arr, arr + n, Compare); cout << endl; for (int i = 0; i < n; i++) { cout << arr[i].number << ' ' << arr[i].score << endl; } return 0; }
Test: . 4 . 1 98 2 90 . 3 98 . 4 89 1 98 3 98 2 90 4 89