From Clomosy Docs
ClomosyAdmin (talk | contribs) No edit summary |
ClomosyAdmin (talk | contribs) No edit summary |
||
| Line 76: | Line 76: | ||
* [[TclArray]] | * [[TclArray]] | ||
* [[Arrays]] | * [[Arrays]] | ||
{{#seo:|title=Insertion Sort in Clomosy - Clomosy Docs}} | |||
{{#seo:|description=Learn about Insertion Sort in Clomosy. A step-by-step guide to understanding and implementing this sorting algorithm in your app.}} | {{#seo:|description=Learn about Insertion Sort in Clomosy. A step-by-step guide to understanding and implementing this sorting algorithm in your app.}} | ||
Latest revision as of 12:51, 24 December 2024
Insertion Sort is similar to sorting a deck of cards. It places each element from the unsorted portion into its correct position within the sorted portion. The algorithm is particularly effective for small and partially sorted datasets.
Steps:
- Consider the first element as sorted.
- Take the next element and insert it into its correct position in the sorted portion.
- Repeat this process until the entire list is sorted.
Example
var
arr: array[0..6] of Integer;
i, j, key, n: Integer;
str: string;
void insertionSort;
{
n = Length(arr);
for (i = 1 to n - 1)
{
key = arr[i];
j = i - 1;
while ((j >= 0) && (arr[j] > key))
{
arr[j + 1] = arr[j];
j = j - 1;
}
arr[j + 1] = key;
}
}
{
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);
insertionSort;
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);
}
