0 votes
72 views
in Data Structure And Algorithm by (3.7k points)
Find the minimum element in a sorted and rotated array in java.

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

Output:- 5

1 Answer

0 votes
by (3.9k 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[0] > 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

Share:- Whatsapp Facebook Facebook


Welcome to Developerhelpway Q&A, where you can ask questions and receive answers from other members of the community.

Categories

...