How to resolve the algorithm Sorting algorithms/Selection sort step by step in the Euphoria programming language

Published on 12 May 2024 09:40 PM

How to resolve the algorithm Sorting algorithms/Selection sort step by step in the Euphoria programming language

Table of Contents

Problem Statement

Sort an array (or list) of elements using the Selection sort algorithm.

It works as follows: First find the smallest element in the array and exchange it with the element in the first position, then find the second smallest element and exchange it with the element in the second position, and continue in this way until the entire array is sorted.

Its asymptotic complexity is   O(n2)   making it inefficient on large arrays. Its primary purpose is for when writing data is very expensive (slow) when compared to reading, eg. writing to flash memory or EEPROM. No other sorting algorithm has less data movement.

Let's start with the solution:

Step by Step solution about How to resolve the algorithm Sorting algorithms/Selection sort step by step in the Euphoria programming language

Source code in the euphoria programming language

function selection_sort(sequence s)
    object tmp
    integer m
    for i = 1 to length(s) do
        m = i
        for j = i+1 to length(s) do
            if compare(s[j],s[m]) < 0 then
                m = j
            end if
        end for
        tmp = s[i]
        s[i] = s[m]
        s[m] = tmp
    end for
    return s
end function

include misc.e
constant s = {4, 15, "delta", 2, -31, 0, "alfa", 19, "gamma", 2, 13, "beta", 782, 1}

puts(1,"Before: ")
pretty_print(1,s,{2})
puts(1,"\nAfter: ")
pretty_print(1,selection_sort(s),{2})

  

You may also check:How to resolve the algorithm Evaluate binomial coefficients step by step in the IS-BASIC programming language
You may also check:How to resolve the algorithm Hello world/Newbie step by step in the Go programming language
You may also check:How to resolve the algorithm Inheritance/Single step by step in the C programming language
You may also check:How to resolve the algorithm Brownian tree step by step in the Ring programming language
You may also check:How to resolve the algorithm List comprehensions step by step in the Visual Prolog programming language