1#include <stdio.h>2 #defineMAX 103typedefintElementType;4 intLength=0;5 intvalue;6typedefstruct {7 ElementType i;8 intlength;9 ElementType Data[max];Ten }sorder; One intMain () { A Sorder L; - //plug data into the order table - for(intI=0; i<max;i++){ thel.data[i]=i+1; -l.length++; - } - //The main algorithm code, to Exchange + for(intI=0;i< (l.length)/2; i++){ -Value=L.data[i]; +l.data[i]=l.data[l.length-i-1]; Al.data[l.length-i-1]=value; at } - //the output is in reverse order - for(intI=0; i<max;i++){ -printf"%d", L.data[i]); - } -}
Q: Design an efficient algorithm that will reverse all elements of the sequential table, requiring the spatial complexity of the algorithm to be O (1);
A: The complexity of this algorithm corresponds to the second problem in the first chapter of the benevolent exercise, the main idea of the algorithm is as follows:
(1) Scan the first half of the order table element, for L.data[i] (I is greater than or equal to 0 less than l.length-1)
(2) Exchange The remaining second half of the corresponding element l.data[l.length-i+1].
Summary: In fact, the main reason is the understanding of the second for Loop, which is also the core code, with the help of the value of the auxiliary variable for an exchange, which is very common in many places.
In-place inverse algorithm of sequential table