Returns the smallest element after rotating an ordered array.

Source: Internet
Author: User

Sequential search can be found, but the time complexity is not the best.

Therefore, binary search can be considered.

In general, if the intermediate data is greater than the first data, it indicates that the intermediate data is a large part, and the smallest number is on the right. Modify the pointer to reloop. If the intermediate data is smaller than the last one, it indicates that the intermediate data is a small part, and the smallest number is on its left. Modify the pointer to reloop.


Some Boundary situations include:

1. No rotation at all

2. if 1 0 1 1 1 or 1 1 1 0 1, the size of the first data, intermediate data, and last data is the same, the smallest data may be on the left or right of the intermediate data, so it cannot be determined and can only be searched in sequence.


# Include <stdio. h> # include <stdlib. h> int search_min (int * data, int length) {int head = 0, result, I; int tail = length-1; int middle = head; // when the initialization is index1, if (data = NULL | length <= 0) return-1; while (data [head]> = data [tail]) {if (tail-head = 1) {middle = tail; break;} middle = (head + tail)/2; if (data [head] = data [tail] & data [head] = data [middle]) {// you can only search in sequence, in this case, it is easy to omit result = data [head + 1]; for (I = head + 2; I <= tail-1; ++ I) {if (result> data [I]) result = data [I];} return result;} if (data [middle]> = data [head]) head = middle; else if (data [middle] <= data [tail]) tail = middle;} return data [middle];} void main () {int d [5] = {1, 1, 3, 4, 5}; printf ("% d \ n", search_min (NULL, 5); getch ();}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.