Skip to content

Commit 415d9a0

Browse files
committed
Add exponential search algorithm implementation with tests and update README
1 parent 41fd54f commit 415d9a0

File tree

3 files changed

+61
-0
lines changed

3 files changed

+61
-0
lines changed

README.md

+11
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,8 @@
33
1. [Linear Search](#linear-search)
44
2. [Jump Search](#jump-search)
55
3. [Binary Search](#binary-search)
6+
4. [Interpolation Search](#interpolation-search)
7+
5. [Exponential Search](#exponential-search)
68

79
# Searching Slgorithms
810

@@ -41,3 +43,12 @@ Interpolation search is a searching algorithm that is used to search for a targe
4143

4244
- **Best Case:** **O(1)** (Target found on first guess)
4345
- **Worst Case:** **O(log log n)** (Assuming uniform distribution)
46+
47+
## Exponential Search
48+
49+
Exponential search is a searching algorithm used to find the position of a target element in a **sorted array** by progressively doubling the size of the search range until the target is within that range. Once the range is found, Binary Search is applied to find the exact index of the target.
50+
51+
### Time Complexity
52+
53+
- **Best Case:** **O(log n)**
54+
- **Worst Case:** **O(log n)**
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
export const exponentialSearch = (
2+
sortedArray: number[],
3+
target: number
4+
): number => {
5+
const length = sortedArray.length
6+
if (length === 0) return -1
7+
8+
let index = 1
9+
10+
while (index < length && sortedArray[index] < target) index = index * 2
11+
12+
let leftIndex = index / 2
13+
let rightIndex = index
14+
while (leftIndex <= rightIndex) {
15+
const midIndex = Math.floor((leftIndex + rightIndex) / 2)
16+
const midElement = sortedArray[midIndex]
17+
if (target === midElement) return midIndex
18+
if (target > midElement) leftIndex = midIndex + 1
19+
else rightIndex = midIndex - 1
20+
}
21+
22+
return -1
23+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
import { describe, it, expect } from 'vitest'
2+
import { exponentialSearch } from '../../../src/algorithms/searching/exponentialSearch'
3+
4+
describe('interpolationSearch', () => {
5+
describe('when array is empty', () => {
6+
it('should return null', () => {
7+
expect(exponentialSearch([], 1)).toBe(-1)
8+
})
9+
})
10+
11+
describe('when array is not empty', () => {
12+
it('should return the correct index', () => {
13+
const vectors = Array.from(
14+
{ length: 10 },
15+
(_, index) => index + 1
16+
).map((positiveInt, index) => ({
17+
array: Array.from({ length: 10 }, (_, index) => index + 1),
18+
target: positiveInt,
19+
expected: index
20+
}))
21+
22+
vectors.forEach(({ array, target, expected }) => {
23+
expect(exponentialSearch(array, target)).toBe(expected)
24+
})
25+
})
26+
})
27+
})

0 commit comments

Comments
 (0)