-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfind_minimum.c
More file actions
72 lines (63 loc) · 1.47 KB
/
find_minimum.c
File metadata and controls
72 lines (63 loc) · 1.47 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
/*
* =====================================================================================
*
* Filename: find_minimum.c
*
* Description: Find Minimum in Rotated Sorted Array.
* Suppose a sorted array is rotated at some pivot unknown to you beforehand.
* (i.e., 0 1 2 4 5 6 7 might become 4 5 6 7 0 1 2).
* Find the minimum element. You may assume no duplicate exists in the array.
*
* Version: 1.0
* Created: 2015/02/25 20时55分40秒
* Revision: none
* Compiler: gcc
*
* Author: Zhu Xianfeng <xianfeng.zhu@gmail.com>
* Organization:
*
* =====================================================================================
*/
#include <stdio.h>
#include <stdlib.h>
static int
_findMin(int arr[], int i, int j)
{
int m;
if (i == j) {
return i;
} else if (i == (j - 1)) {
if (arr[i] < arr[j]) {
return i;
} else {
return j;
}
}
m = (i + j) / 2;
if (arr[i] > arr[m]) {
return _findMin(arr, i, m);
} else if (arr[m] > arr[j]) {
return _findMin(arr, m, j);
} else {
/* Normal sorted list */
return i;
}
}
int
findMin(int num[], int n)
{
int idx;
idx = _findMin(num, 0, n - 1);
return num[idx];
}
int main(int argc, char *argv[])
{
int arr1[] = {4, 5, 6, 7, 0, 1, 2};
int arr2[] = {1, 2, 3, 4, 5, 6, 7};
int min;
min = findMin(arr1, 7);
printf("Min: %d\n", min);
min = findMin(arr2, 7);
printf("Min: %d\n", min);
return 0;
}