Sort Functions

From Multi Theft Auto: Wiki
Revision as of 14:37, 7 October 2017 by Dretax (talk | contribs) (Created page with "==Code== '''Sorting Algorithms provided by DreTaX <syntaxhighlight lang="lua"> table InsertSortingByIndex(table t, int SortByKey) table FixedBubbleSortingByIndex(table t, int...")
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to navigation Jump to search

Code

Sorting Algorithms provided by DreTaX

table InsertSortingByIndex(table t, int SortByKey)
table FixedBubbleSortingByIndex(table t, int SortByKey)
Click to collapse [-]
Function source

Insert Sorting works possibly the fastest way If we don't know how sorted our array is. You need to specify a table, and the table's index which we will be using to sort with. For Example if our table has values like this, then you would specify 3: {player, vehicle, playerid, npc} local table = InsertSortingByIndex(table, 3)

function InsertSortingByIndex(array, e)
	local data = array
	for i = 2, #data do
		local j = i - 1
		local ass = data[i]
		while j > 0 and data[j][e] > ass[e] do
			data[j + 1] = data[j]
			j = j - 1
		end
		data[j + 1] = ass
	end
	return data
end

o(n^2) Sorting algorithm for lua.

function FixedBubbleSortingByIndex(array, e)
	local data = array
	local i = #data
	while i >= 2 do
		local idx = 0
		for j = 1, (i - 1) do
			if data[j][e] > data[j + 1][e] then
				local holder = data[j][e]
				data[j][e] = data[j + 1][e]
				data[j + 1][e] = holder
				idx = j
			end
		end
		i = idx
	end
	return data
end

Usage

local TestArray = {
	{1, "test"},
	{33, "test"},
	{-32, "test"},
	{-1, "test"},
	{5, "test"},
	{11, "test"},
	{968, "test"},
	{723, "test"},
	{33, "test"},
	{16, "test"},
	{4, "test"},
	{5, "test"},
}
local SortedTestArray = FixedBubbleSortingByIndex(TestArray, 1)
for k, v in pairs(SortedTestArray) do
	outputChatBox("Value: " .. v[1])
end
local SortedTestArray2 = InsertSortingByIndex(TestArray, 1)
for k, v in pairs(SortedTestArray2) do
	outputChatBox("Value: " .. v[1])
end