How do you find the largest and smallest number in an unsorted array?

So this is what I have been created so far, but I dont know how to find the smallest number in that case it is 1, but how can I find it, if my integer starts at 1 :expressionless:

so what I am trying is to print 8 and 1, but actually I had problems to find 1, so how can I fix it?
**

The script should even work if I change the start and the end number - also even when I unsort everything.

**

local numbers = {1,4,3,2,7,5,6,8}

function getlargesthighestnumber(a, largest)
	local total = 0
	for i = 1, #a do
		if i > total then
			total = i
		end
	end
	return total 
end

local miss = getlargesthighestnumber(numbers, 1)
print(miss)
1 Like

You can use math.min and math.max:

local numbers = {1,4,3,2,7,5,6,8}

print(math.max(table.unpack(numbers))) --> 8
print(math.min(table.unpack(numbers))) --> 1

The former returns the smallest number, the latter returning the largest. If you want the array to be modified, you can use table.sort, which by default sorts in ascending order.

table.sort(numbers)
print(numbers[1]) --> 1
print(numbers[#numbers]) --> 8
6 Likes

oh you was really fast well done!