Last active
November 16, 2021 21:04
-
-
Save arce/e8d0d2ad3573a4f6677220d29ddec4ab to your computer and use it in GitHub Desktop.
Search Algorithms
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function seqSearch(x,A,n) | |
local i=0 | |
while (i < n) do | |
if (x == A[i]) then | |
return i | |
end | |
i = i + 1 | |
end | |
return -1 | |
end | |
function sortSeach(x,A,n) | |
local i = 0 | |
while (i < n) do | |
if (x == A[i]) then | |
return i | |
elseif (x > A[i]) then | |
return -1 | |
end | |
i = i + 1 | |
end | |
return -1 | |
end | |
function binSearch(x,A,n) | |
local left = -1 | |
local right = n | |
while( left+1 < right) do | |
local i = (left + right) / 2 | |
if (x < A[i]) then | |
right = i | |
elseif (x > A[i]) then | |
left = i | |
else | |
return i | |
end | |
end | |
return -1 | |
end | |
function interpolationSearch(x, A, n) | |
local left = 0 | |
local right = (n - 1) | |
while (left <= right and x >= A[left] and x <= A[right]) do | |
if (left == right) then | |
if (arr[left] == x) then return left end | |
return -1 | |
end | |
local i = left + (right - left) // | |
((A[right] - A[left]) * (x - A[left])) | |
if (x < A[i]) then | |
right = i | |
elseif (x > A[i]) then | |
left = i | |
else | |
return i | |
end | |
end | |
return -1 | |
end | |
function jumpSearch(x, A, n) | |
local step = math.sqrt(n) | |
local prev = 0 | |
while (A[min(step, n)-1] < x) do | |
prev = step; | |
step = step + math.sqrt(n) | |
if (prev >= n) then | |
return -1; | |
end | |
while (A[prev] < x) do | |
prev = prev + 1 | |
if (prev == min(step, n)) then | |
return -1 | |
end | |
end | |
if (A[prev] == x) then | |
return prev | |
end | |
end | |
return -1 | |
end | |
local array = {} | |
for i=0,10 do | |
array[i] = i | |
end | |
local x = seqSearch(15,array,10) | |
print(x) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment