1. How do I use a language with a library to implement a sorting algorithm representation and sorting collection if memory is not missing?
1) You can use the Quick sort qsort(refer to from Cplusplus) in C for the following code:
1 /*Qsort Example*/2#include <stdio.h>/*printf*/3#include <stdlib.h>/*qsort*/4 5 intValues[] = { +,Ten, -, -, -, - };6 7 intCompareConst voidAConst void*b)8 {9 return(*(int*) A-* (int*) b);Ten } One A intMain () - { - intN; theQsort (values,6,sizeof(int), compare); - for(n =0; N <6; n++) -printf"%d", Values[n]); - return 0; +}
qsort
About Qsort, there is a good blog post, you can refer to.
2) You can use the C + + Standard Template Library function sort(refer to from Cplusplus) with the following code:
1 //Sort Algorithm Example2#include <iostream>//Std::cout3#include <algorithm>//Std::sort4#include <vector>//std::vector5 6 BOOLMyFunctionintIintj) {return(I <j); }7 8 structMyClass {9 BOOL operator() (intIintj) {return(I <j); }Ten } MyObject; One A intMain () { - intMyints[] = { +, in, A, $, -, the, -, - }; -std::vector<int> Myvector (myints, myints +8);// All in all the - //using default comparison (operator <): -Std::sort (Myvector.begin (), Myvector.begin () +4);//(a) - + //using function as comp -Std::sort (Myvector.begin () +4, Myvector.end (), myfunction);//(+) + A //using object as Comp atStd::sort (Myvector.begin (), Myvector.end (), MyObject);//(a) - - //Print out content: -Std::cout <<"Myvector contains:"; - for(std::vector<int>::iterator it = Myvector.begin (); It! = Myvector.end (); ++it) -Std::cout <<' '<< *it; inStd::cout <<'\ n'; - to return 0; +}
Sort
3) The same functionality can be accomplished using the C + + Standard template reservoir set :
Excerpt from a blog post on the Set container: The realization of the red and black tree balance binary search tree data structure, when inserting elements, it will automatically adjust the binary tree arrangement, put elements in the appropriate position, to ensure that each sub-tree root node key value is greater than the left subtree all nodes of the key value, less than the right subtree of all nodes of the key Also ensure that the height of the left subtree of the root node is equal to the height of the right sub-tree. The key values can be traversed from small to large using the middle order traversal (with iterators).
Refer to Cplusplus for a more detailed description of the set container.
The specific code is as follows:
1#include <iostream>2#include <Set>3 using namespacestd;4 5 intMain ()6 {7 intMyints[] = { $, at, the, the, - };8 Set<int> MySet (myints, myints +5);//Use the ' Set ' member function ' Insert ' is also OK.9 Ten Set<int>::iterator ITR =Myset.begin (); One for(; ITR! = Myset.end (); itr++) A { -cout << *itr <<" ";// all, at - } the - return 0; -}
Set
"Programming Zhu Ji Nanxiong" (2nd edition) Chapter One ": After-school exercises