注意:应该有一个额外的决定是在 {4,9} 之间还是在 {9,8} 之间进行切割。(我只是添加一个;-)
#include <stdio.h>
int array[] = {1,2,3,4,9,8,7,11,12,14};
unsigned findrev(int *arr, unsigned len, unsigned *ppos);
void revrev(int *arr, unsigned len);
unsigned findrev(int *arr, unsigned len, unsigned *ppos)
{
unsigned zlen,pos;
for(zlen=pos=0; pos < len-1; pos++ ) {
if (arr[pos+1] < arr[pos]) zlen++;
else if (zlen) break;
}
if (zlen) *ppos = pos - zlen++;
return zlen;
}
void revrev(int *arr, unsigned len)
{
unsigned pos;
for (pos = 0; pos < --len; pos++) {
int tmp;
tmp = arr[pos];
arr[pos] = arr[len] ;
arr[len] = tmp;
}
}
int main(void)
{
unsigned start,len;
len = findrev(array, 10, &start);
printf("Start=%u Len=%u\n", start, len);
revrev(array+start, len);
for (start=0; start < 10; start++) {
printf(" %d", array[start] );
}
printf("\n" );
return 0;
}
注意:反向运行的长度也可以通过二进制搜索大于(或等于)反向序列的第一个元素的第一个值来找到。