Sorting algorithms/Shell sort: Difference between revisions
Content added Content deleted
(Removed comments line in J language) |
|||
Line 320: | Line 320: | ||
Create the following script and load it to a J session. |
Create the following script and load it to a J session. |
||
<lang j>shellSort=: verb define |
<lang j>shellSort=: verb define |
||
NB. Loop through all values |
|||
data=. y |
data=. y |
||
for_xyz. y do. |
for_xyz. y do. |
||
NB. remove the already sorted values |
|||
temp=. xyz_index }. data |
temp=. xyz_index }. data |
||
NB. Find the index position of the smallest value in the set |
|||
nvidx=. xyz_index + temp i. <./ temp |
nvidx=. xyz_index + temp i. <./ temp |
||
NB. Now switch the values |
|||
data=. ((xyz_index, nvidx) { data) (nvidx, xyz_index) } data |
data=. ((xyz_index, nvidx) { data) (nvidx, xyz_index) } data |
||
end. |
end. |
||
NB. Return the sorted data |
|||
data |
data |
||
)</lang> |
)</lang> |
||
Line 333: | Line 338: | ||
[data=. 10 ? 100 |
[data=. 10 ? 100 |
||
51 18 81 46 11 54 74 63 56 76 |
51 18 81 46 11 54 74 63 56 76 |
||
NB. Now execute the script passing the generated data |
|||
shellSort data |
shellSort data |
||
11 18 46 51 54 56 63 74 76 81 |
|||
</lang> |
|||
Note that J already has a very efficient sorting command and using the code above is not using J effectively. |
|||
<lang j> /:~ :/: data |
|||
11 18 46 51 54 56 63 74 76 81 |
11 18 46 51 54 56 63 74 76 81 |
||
</lang> |
</lang> |