Hand-Crank algorithm (also called three-time reversal algorithm)
Title: ABCDEFG The string into a EFGABCD, requiring space complexity O (1).
Answer:
- The first step: turn the substring ABCD into DCBA. The source string becomes DCBAEFG
- Step Two: Turn the string EFG into a GFE. The source string becomes DCBAGFE
- Step three: Invert the entire string DCBAGFE and turn it into a efgabcd.
Hand-crank algorithms are often used to rotate strings. At the same time, hand-crank algorithm can also be used to do in-situ merge sort, to achieve space O (1).
Core code:
void shiftblocks (int arr[], int start, int pos, int end) {reverse (arr,start,pos-1); reverse (arr,pos,end); reverse (arr, Start,end);} void reverse (int arr[], int start, int end) {for (int i=start, j=end; i<j; i++,j--) {int temp = Arr[i];arr[i] = Arr[j];arr [j] = temp;}}
String inversion--hand-crank algorithm