# Find the minimum element in a sorted and rotated array in java

179 views
Find the minimum element in a sorted and rotated array in java.

int arr[] = {10,20,30,40,5,6,7,8};

Output:- 5

by (4.4k points)

To find the minimum element in sorted and rotated array in java. See the following code to search minimum element in sorted and rotated array.

Following code takes the Time Complexity is O(logN).

See the running code to find minimum element in sorted and rotated array:-

package com.dev.search;

public class FindMinimumInSortedAndRotatedArray {

public static void main(String[] args) {

int arr[] = {10,20,30,40,5,6,7,8};

int max = findMinimumInSortedAndRoted(arr);

System.out.println("Minimum: " + arr[max]);

}

//Time Complexity O(logN)

private static int findMinimumInSortedAndRoted(int[] arr) {

return getMinimum(arr, 0, arr.length-1);

}

private static int getMinimum(int[] arr, int l, int h) {

//Base cases

if(l>h)

return -1;

if(l==h)

return l;

int middle = (l+h)/2;

if(arr[middle] < arr[middle-1]) {

return middle;

}

if(arr > arr[middle]) {//Go to left in array for finding pivot

return getMinimum(arr, l, middle-1);

}else{//Go to right in array for finding pivot

return getMinimum(arr, middle+1, h);

}

}

}

Output:-

Minimum: 5