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

Published on 12 May 2024 09:40 PM

How to resolve the algorithm Sorting algorithms/Selection sort step by step in the Haxe 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 Haxe programming language

Source code in the haxe programming language

class SelectionSort {
  
  public static function sort<T>(arr:Array<T>) {
    var len = arr.length;
    for (index in 0...len) {
      var minIndex = index;
      for (remainingIndex in (index+1)...len) {
        if (Reflect.compare(arr[minIndex], arr[remainingIndex]) > 0)
          minIndex = remainingIndex;
      }
      if (index != minIndex) {
        var temp = arr[index];
        arr[index] = arr[minIndex];
        arr[minIndex] = temp;
      }
    }
  }
}

class Main {
  static function main() {
    var integerArray   = [1, 10, 2, 5, -1, 5, -19, 4, 23, 0];
    var floatArray = [1.0, -3.2, 5.2, 10.8, -5.7, 7.3, 
                      3.5, 0.0, -4.1, -9.5];
    var stringArray = ['We', 'hold', 'these', 'truths', 'to', 
                       'be', 'self-evident', 'that', 'all', 
                       'men', 'are', 'created', 'equal'];
    Sys.println('Unsorted Integers:' + integerArray);
    SelectionSort.sort(integerArray);
    Sys.println('Sorted Integers:  ' + integerArray);
    Sys.println('Unsorted Floats:  ' + floatArray);
    SelectionSort.sort(floatArray);
    Sys.println('Sorted Floats:    ' + floatArray);
    Sys.println('Unsorted Strings: ' + stringArray);
    SelectionSort.sort(stringArray);
    Sys.println('Sorted Strings:   ' + stringArray);
  }
}


  

You may also check:How to resolve the algorithm Generic swap step by step in the Ursala programming language
You may also check:How to resolve the algorithm Sudan function step by step in the XPL0 programming language
You may also check:How to resolve the algorithm Longest increasing subsequence step by step in the Go programming language
You may also check:How to resolve the algorithm Flatten a list step by step in the zkl programming language
You may also check:How to resolve the algorithm Sorting algorithms/Selection sort step by step in the BCPL programming language