From Clomosy Docs
No edit summary |
ClomosyAdmin (talk | contribs) No edit summary |
||
| (One intermediate revision by one other user not shown) | |||
| Line 13: | Line 13: | ||
<b>Example</b><br> | <b>Example</b><br> | ||
<pre> | <pre> | ||
var | var | ||
| Line 76: | Line 76: | ||
} | } | ||
</pre> | </pre> | ||
<h2> See Also </h2> | <h2> See Also </h2> | ||
| Line 146: | Line 81: | ||
* [[TclArray]] | * [[TclArray]] | ||
* [[Arrays]] | * [[Arrays]] | ||
{{#seo:|title=Selection Sort Explained - Clomosy Docs}} | |||
{{#seo:|description=Learn Selection Sort in Clomosy Docs. A step-by-step guide to implementing this simple yet efficient sorting algorithm in mobile app development.}} | |||
Latest revision as of 11:33, 20 December 2024
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
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);
}