Advertisement
Guest User

Untitled

a guest
Dec 16th, 2013
98
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
F# 1.09 KB | None | 0 0
  1. open System
  2.  
  3. // Array of random numbers with the property that A[1] > A[2] and A[n] > A[n-1]
  4. let A =
  5.     [|
  6.     22; 21; 21; 62; 11
  7.     57; 10; 69; 29; 12
  8.     81; 90; 51; 89; 48
  9.     82; 11; 8; 43; 69
  10.     |]
  11.  
  12. // Finds a local min in log(n) time
  13. let rec getLocalMin (A:int array) =
  14.     let n = A.Length
  15.  
  16.     // Stores the first, last, and middle elements of the array
  17.     let first = A.[0]
  18.     let middle = A.[n/2]
  19.     let last = A.[n-1]
  20.  
  21.     // Stores the elements to the left and right of the middle element
  22.     let left = A.[n/2 - 1]
  23.     let right = A.[n/2 + 1]
  24.  
  25.     // Is middle a local min?
  26.     match (left >= middle) && (right >= middle) with
  27.     | true -> middle                                                 // If it is a local min, return it
  28.     | false when left <= middle -> getLocalMin (Array.sub A 0 (n/2)) // If the left is smaller, find the local min of elements between 0 and n/2
  29.     | false -> getLocalMin (Array.sub A (n/2) (n-1))                 // If the right is smaller, find the local min of elements between n/2 and n-1
  30.  
  31. let min = getLocalMin A
  32. printf "%i" min
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement