|
| 1 | +package main |
| 2 | + |
| 3 | +import ( |
| 4 | + "fmt" |
| 5 | +) |
| 6 | + |
| 7 | +func main() { |
| 8 | + // Example sorted array for testing |
| 9 | + arr := []int{1, 3, 5, 7, 9, 11, 13, 15, 17, 19} |
| 10 | + |
| 11 | + // Test binary search |
| 12 | + target := 7 |
| 13 | + index := BinarySearch(arr, target) |
| 14 | + fmt.Printf("BinarySearch: %d found at index %d\n", target, index) |
| 15 | + |
| 16 | + // Test recursive binary search |
| 17 | + recursiveIndex := BinarySearchRecursive(arr, target, 0, len(arr)-1) |
| 18 | + fmt.Printf("BinarySearchRecursive: %d found at index %d\n", target, recursiveIndex) |
| 19 | + |
| 20 | + // Test find insert position |
| 21 | + insertTarget := 8 |
| 22 | + insertPos := FindInsertPosition(arr, insertTarget) |
| 23 | + fmt.Printf("FindInsertPosition: %d should be inserted at index %d\n", insertTarget, insertPos) |
| 24 | +} |
| 25 | + |
| 26 | +// BinarySearch performs a standard binary search to find the target in the sorted array. |
| 27 | +// Returns the index of the target if found, or -1 if not found. |
| 28 | +func BinarySearch(arr []int, target int) int { |
| 29 | + left, right := 0, len(arr)-1 |
| 30 | + for left <= right { |
| 31 | + mid := (left + right) / 2 |
| 32 | + if arr[mid] < target { |
| 33 | + left = mid + 1 |
| 34 | + } else if arr[mid] > target { |
| 35 | + right = mid - 1 |
| 36 | + } else { |
| 37 | + return mid |
| 38 | + } |
| 39 | + } |
| 40 | + |
| 41 | + return -1 |
| 42 | +} |
| 43 | + |
| 44 | +// BinarySearchRecursive performs binary search using recursion. |
| 45 | +// Returns the index of the target if found, or -1 if not found. |
| 46 | +func BinarySearchRecursive(arr []int, target int, left int, right int) int { |
| 47 | + if left > right { |
| 48 | + return -1 |
| 49 | + } |
| 50 | + |
| 51 | + mid := (left + right) / 2 |
| 52 | + if arr[mid] == target { |
| 53 | + return mid |
| 54 | + } else if arr[mid] < target { |
| 55 | + return BinarySearchRecursive(arr, target, mid+1, right) |
| 56 | + } else { |
| 57 | + return BinarySearchRecursive(arr, target, left, mid-1) |
| 58 | + } |
| 59 | +} |
| 60 | + |
| 61 | +// FindInsertPosition returns the index where the target should be inserted |
| 62 | +// to maintain the sorted order of the array. |
| 63 | +func FindInsertPosition(arr []int, target int) int { |
| 64 | + left, right := 0, len(arr) |
| 65 | + for left < right { |
| 66 | + mid := (left + right) / 2 |
| 67 | + if arr[mid] < target { |
| 68 | + left = mid + 1 |
| 69 | + } else { |
| 70 | + right = mid |
| 71 | + } |
| 72 | + } |
| 73 | + |
| 74 | + return left |
| 75 | +} |
0 commit comments