Question 1: rotate an array with n elements at I position to the right.
Example:
Input: Rotate (1, 2, 3, 4, 5, 6, 7, 8, 9) Three positions.
Output: (7, 8, 9, 1, 2, 3, 4, 5, 6)
Problem 2: (cracking the coding interview 9.3) given a sorted array of N integers that has been rotated an unknown number of times, give an O (log n) algorithm that finds an element in the array. you may assume that the array was originally sorted in increasing order.
Example:
Input: find 5 in array (15 16 19 20 25 1 3 4 5 7 10 14)
Output: 8 (the index of 5 in the array)
Idea: we still use the binary method for searching, so we can make more judgments when searching.
int FindRotatedSortedArray(const int nVal, const int *pArr, const int nlength){int idxL = 0;;int idxR = nlength - 1;int idxM = (idxL + idxR) / 2;while (idxR >= idxL){idxM = (idxL + idxR) / 2;if (nVal == pArr[idxM])return idxM;if (pArr[idxL] < pArr[idxR])// arr not rotated. 10 ,,,, 15 ,,,, 20{if (pArr[idxM] > nVal)//search leftidxR = idxM - 1;else//search rightidxL = idxM + 1;}else{if (pArr[idxM] < pArr[idxL] && pArr[idxM] < pArr[idxR]) // 20 ,,,, 5 ,,,, 10{if (nVal < pArr[idxM] || nVal >= pArr[idxL])// 20 ,(25 ,, 4), 5 ,,,, 10idxR = idxM - 1; //search leftelse// 20 ,,,, 5 ,,(6),, 10idxL = idxM + 1; // search right}else if (pArr[idxM] >= pArr[idxL] && pArr[idxM] > pArr[idxR])// 20 ,,,, 25 ,,,, 10{if (nVal > pArr[idxM] || nVal <= pArr[idxR])// 20 ,,,, 25 ,(30 ,, 5), 10{idxL = idxM + 1; //search right}else // 20 ,,(23),, 25 ,,,, 10{idxR = idxM - 1; //search left}}}}return -1;}
Question 3: Given A sorted array of N integers that has been rotated an unknown number of times, give an O (log n) algorithm that finds the index of the minimum element.
Example:
Input: find 5 in array (15 16 19 20 25 1 3 4 5 7 10 14)
Output: 5 (the index of 1 in the array)
int FindMinimun(const int *pArr, const int nLength){if (NULL == pArr)return -1;int idxL = 0;int idxR = nLength - 1;int idxM;while (idxL <= idxR){if (pArr[idxL] <= pArr[idxR])// ,,, 5, ,,, 10, ,,,return idxL;if (idxL + 1 == idxR && pArr[idxL] > pArr[idxR])// ,,, 10, 1, ,,,return idxR;idxM = (idxL + idxR)/2;if (pArr[idxM] >= pArr[idxL])// ,,, 10, ,,, 20, ,,, 1, ,,,idxL = idxM + 1;else if (pArr[idxM] <= pArr[idxR]) // ,,, 10, ,,, 5, ,,, 20, ,,,idxR = idxM;elsereturn -1;}return -1;}