From Clomosy Docs
Selection Sort works by repeatedly selecting the smallest element from the unsorted portion of the dataset and appending it to the end of the sorted portion.
In the first pass, the smallest value is found and moved to the 0 index. The remainder of the unsorted array is then searched for the new minimum, which is placed in the 1 index, and so on. For an array of n elements, this will require n passes.
Steps:
- Find the smallest element from the unsorted portion of the list.
- Append this element to the end of the sorted portion.
- Repeat this process until the entire list is sorted.
Example:
- TRObject Syntax
var
arr: array[0..6] of Integer;
i, j, minIdx, n, temp: Integer;
str: string;
void selectionSort;
{
n = Length(arr);
for (i = 0 to n - 1)
{
minIdx = i;
for (j = i + 1 to n - 1)
{
if (arr[j] < arr[minIdx])
{
minIdx = j;
}
}
temp = arr[minIdx];
arr[minIdx] = arr[i];
arr[i] = temp;
}
}
{
arr[0] = 12;
arr[1] = 11;
arr[2] = 13;
arr[3] = 5;
arr[4] = 1;
arr[5] = 7;
arr[6] = 9;
str = 'Unordered array: ';
for (i = 0 to Length(arr)-1)
{
str = str + IntToStr(arr[i]) + ' ';
}
ShowMessage(str);
selectionSort;
str = 'Array sorted from smallest to largest: ';
for (i = 0 to Length(arr)-1)
{
str = str + IntToStr(arr[i]) + ' ';
}
ShowMessage(str);
str = 'Array sorted from largest to smallest: ';
for (i = Length(arr)-1 downto 0)
{
str = str + IntToStr(arr[i]) + ' ';
}
ShowMessage(str);
}
- Base Syntax
var
arr: array[0..6] of Integer;
i, j, minIdx, n, temp: Integer;
str: string;
procedure selectionSort;
begin
n := Length(arr);
for i := 0 to n - 1 do
begin
minIdx := i;
for j := i + 1 to n - 1 do
begin
if arr[j] < arr[minIdx] then
begin
minIdx := j;
end;
end;
temp := arr[minIdx];
arr[minIdx] := arr[i];
arr[i] := temp;
end;
end;
begin
arr[0] := 12;
arr[1] := 11;
arr[2] := 13;
arr[3] := 5;
arr[4] := 1;
arr[5] := 7;
arr[6] := 9;
str := 'Unordered array: ';
for i := 0 to Length(arr)-1 do
begin
str := str + IntToStr(arr[i]) + ' ';
end;
ShowMessage(str);
selectionSort;
str := 'Array sorted from smallest to largest: ';
for i := 0 to Length(arr)-1 do
begin
str := str + IntToStr(arr[i]) + ' ';
end;
ShowMessage(str);
str := 'Array sorted from largest to smallest: ';
for i := Length(arr)-1 downto 0 do
begin
str := str + IntToStr(arr[i]) + ' ';
end;
ShowMessage(str);
end;