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

Published on 12 May 2024 09:40 PM
#J

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

Source code in the j programming language

selectionSort=: verb define
  data=. y
  for_xyz. y do.
    temp=. xyz_index }. data
    nvidx=. xyz_index + temp i. <./ temp
    data=. ((xyz_index, nvidx) { data) (nvidx, xyz_index) } data
  end.
  data
)


ix=: C.~ <@~.@(0, (i. <./)) 
ss1=: ({. , $:@}.)@ix^:(*@#)


   [data=. 6 15 19 12 14 19 0 17 0 14
6 15 19 12 14 19 0 17 0 14
   selectionSort data
0 0 6 12 14 14 15 17 19 19
   ss1 data
0 0 6 12 14 14 15 17 19 19


  

You may also check:How to resolve the algorithm Extreme floating point values step by step in the C programming language
You may also check:How to resolve the algorithm Globally replace text in several files step by step in the Ring programming language
You may also check:How to resolve the algorithm Hello world/Standard error step by step in the Argile programming language
You may also check:How to resolve the algorithm Determine if a string is numeric step by step in the PL/I programming language
You may also check:How to resolve the algorithm Pythagoras tree step by step in the JavaScript programming language