Fetching Latest User Using Binary search algorithm

This code is a example to fetch latest user by Binary search algorithm

The number is not 100% Correct,But the User Exists

-- I translated my comments into english,some is not correct because my english is shit
local players = game:GetService("Players")

function checkUserExists(id)
	local res = false
	pcall(function()
		res = players:GetNameFromUserIdAsync(id)
	end)
	return res
end
function search(lastnum,startnum)
	local start = startnum or 2047741938
	local last = lastnum or 10000000000000000
	--
	local min_id = start
	local res = 0
	local function searchNext()
		  
		-- Max - min
		local a = math.round((last - min_id) / 2)
		-- a + min 
		local id = min_id + a
		--
		wait(0.1)

		if checkUserExists(id) then
			-- If found answer,check next item is nil
			if checkUserExists(id + 1) == nil or  (last - min_id) == 1 then
				 res = id
				return id
			end
			warn("Left " .. min_id .. "~" .. last)
			min_id = id
			
			searchNext()
		else
			-- Check Account Mischeck
			if (last - min_id) == 1 then
				warn("Found")
				print(min_id)
				res = min_id
				return
				
			end
			if checkUserExists(id + 1) then
				warn('Might be deleted account')
				min_id = id + 1
				searchNext()
				return
			 
			else
				warn( (last - min_id) )
				warn("Right " .. min_id .. "~" .. last .. " Searched ID" .. id)
				last = id
				searchNext()
			end
			 
			 
		end
	end
	searchNext()
 	return  res
 end

1 Like