Insert algorithm, Greedy Algorithm
The insert learning algorithm is a sorted in place algorithm that sorts data in the original array or vector without re-allocating memory.
Its pseudocode is
# Define SIZE 6 // array reference implementation method of the Insertion Algorithm void insertion_sort (int (& array) [SIZE]) {int key; for (int j = 1; j <SIZE; j ++) {key = array [j]; int I = J-1; while (I> = 0 & array [I]> key) {array [I + 1] = array [I]; -- I;} array [I + 1] = key ;}
When the array reference is used as the form parameter, the array size must be fixed and can be in the form of # define.
3. Passing Parameters Using vector
Void insert_sort (vector <int> & array) // when vector <int> array is used as the form parameter, // the content of the object in the original vector cannot be changed, {// when using container references, indexes can be normally changed // indexed using vector subscript, same as the string and array int key; for (int j = 1; j <array. size (); j ++) {key = array [j]; int I = J-1; while (I> = 0 & array [I]> key) {array [I + 1] = array [I]; -- I;} array [I + 1] = key ;}}
Here, there is a mismatch, that is, array. size () is in the form of unsigned int, but j is of the int type. problems may occur when comparing the two. If I and j are defined as the unsigned type, when I = 0 in a while LOOP, -- I is of the unsigned type, so I is changed to 232, so array [I] will overflow. If you must use unsigned int I, j, you must set a post in the main function. The settings of the guard post are shown below.
4. Use iterator
Void insertSort (vector <int> & array) {vector <int>: iterator it = array. begin () + 1; for (it + = 1; it! = Array. end (); ++ it) {int key = * it; vector <int >:: iterator ita = it-1; while (ita> = array. begin () + 1 & (* ita)> key) {* (ita + 1) = * ita; -- ita;} * (ita + 1) = key ;}} int main () {vector <int> A;. push_back (INT_MIN); // you can set the guard to continue running the program. A. push_back (5);. push_back (2);. push_back (4);. push_back (3);. push_back (1);. push_back (6); // insert_sort (A); insertSort (A); vector <int >:: iterator it =. begin () + 1; while (it! = A. end () {cout <* it <"\ t"; ++ it ;}}