Lately I used the great sorting algorythm made by Rebuilder from Habr.com. It served me well, but it sorts only positive integers, and recently I run into the need to sort negatives as well. For now I use QuickSort, but since the array is very large (10k+ elements), I wonder if one could modify RadixSort for this task.
There is the procedure as for now. Comment translation is mine, sorry if I get something wrong.
procedure RSort(var m: array of Longword);
//--------------------------------------------------
procedure Sort_step(var source, dest, offset: array of Longword; const num: Byte);
var i,temp : Longword;
k : Byte;
begin
for i := High(source) downto 0 do
begin
temp := source[i];
k := temp SHR num;
dec(offset[k]);
dest[offset[k]] := temp;
end;
end;
//--------------------------------------------------
// Объявляем массив корзин первым, для выравнивания на стеке
// Creating the bin array first for aligning at the stack
var s : array[0..3] of array[0..255] of Longword;
i,k : longword;
// Смещение байт внутри переменной k
// Byte offset inside of variable k
offset : array[0..3] of byte absolute k;
m_temp : array of Longword;
begin
SetLength(m_temp, Length(m));
// Быстрая очистка корзин
// Quick bin clear
FillChar(s[0], 256 * 4 * SizeOf(Longword), 0);
// Заполнение корзин
// Filling bins
for i := 0 to High(m) do
begin
k := m[i];
Inc(s[0,offset[0]]);
Inc(s[1,offset[1]]);
Inc(s[2,offset[2]]);
Inc(s[3,offset[3]]);
end;
// Пересчёт смещений для корзин
// Recalculating bin offsets
for i := 1 to 255 do
begin
Inc(s[0,i], s[0,i-1]);
Inc(s[1,i], s[1,i-1]);
Inc(s[2,i], s[2,i-1]);
Inc(s[3,i], s[3,i-1]);
end;
// Вызов сортировки по байтам от младших к старшим
// Sorting by byte, from least to most
Sort_step(m, m_temp, s[0], 0);
Sort_step(m_temp, m, s[1], 8);
Sort_step(m, m_temp, s[2], 16);
Sort_step(m_temp, m, s[3], 24);
SetLength(m_temp, 0);
end;
Link: https://habr.com/ru/post/484224/
I found some helpful advice on the Internet, including StackOverflow, but I met two problems:
There are too many different solutions and I can't choose the optimal one for Delphi.
I lack the knowledge and skill to implement them correctly. I've tried some and get wrong results.
So, could someone modify the given function and explain to me what they did and why?