我们有一个任务来搜索排序后向右移动的数组的最小元素。例如:[1, 5, 6, 19, 56, 101] 变为 [19, 56, 101, 1, 5, 6]。该方法应该使用分而治之算法来实现,并且它应该具有比 O(n) 更好的渐近时间复杂度。编辑:我忘了补充一点,数组中的元素是唯一的。
我已经实现了一种方法,想问一下这是否比 O(n) 更好,是否有改进我的方法的方法。
public class FindMinimum {
public void findMinimum(int[] arr) {
// the recursive method ends when the length of the array is smaller than 2
if (arr.length < 2) {
return;
}
int mid = arr.length / 2;
/*
* if the array length is greater or the same as two, check if the middle
* element is smaller as the element before that. And print the middle element
* if it's true.
*/
if (arr.length >= 2) {
if (arr[mid - 1] > arr[mid]) {
System.out.println("Minimum: " + arr[mid]);
return;
}
}
/*
* separate the array in two sub-arrays through the middle and start the method
* with those two arrays again.
*/
int[] leftArr = new int[mid];
int[] rightArr = new int[arr.length - mid];
for (int i = 0; i < mid; i++) {
leftArr[i] = arr[i];
}
for (int i = mid; i < arr.length; i++) {
rightArr[i - mid] = arr[i];
}
findMinimum(leftArr);
findMinimum(rightArr);
}
}
萧十郎
临摹微笑
相关分类