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

Published on 12 May 2024 09:40 PM
#Jq

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

Source code in the jq programming language

# Sort any array
def selection_sort:
  def swap(i;j): if i == j then . else .[i] as $tmp | .[i] = .[j] | .[j] = $tmp end;
  length as $length
  | reduce range(0; $length) as $currentPlace
      # state: $array
      ( .;
        . as $array
        | (reduce range( $currentPlace; $length) as $check
            # state: [ smallestAt, smallest] except initially [null]
            ( [$currentPlace+1] ;
               if length == 1 or $array[$check] < .[1]
               then [$check, $array[$check] ]
               else .
               end
             )) as $ans
          | swap( $currentPlace; $ans[0] )
          ) ;

[1, 3.3, null, 2, null, [1,{"a":1 }] ] | selection_sort

  

You may also check:How to resolve the algorithm Delete a file step by step in the Ada programming language
You may also check:How to resolve the algorithm Singleton step by step in the Go programming language
You may also check:How to resolve the algorithm Collections step by step in the Go programming language
You may also check:How to resolve the algorithm Josephus problem step by step in the Arturo programming language
You may also check:How to resolve the algorithm Largest int from concatenated ints step by step in the AutoHotkey programming language