Created
March 8, 2018 10:02
-
-
Save v64/74f9d9d726c0fd9399f29ed4862cf8de to your computer and use it in GitHub Desktop.
Quicksort in J
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #!/Users/v64/.bin/j | |
| NB. qsort is the implementation of the quicksort algorithm in J. | |
| NB. | |
| NB. With just two small modifications, the output of the algorithm | |
| NB. can be changed to output a nested data structure illustrating | |
| NB. the pivot points of the sort. | |
| NB. | |
| NB. Interesting demonstration about the strength of expressing | |
| NB. algorithms this way. | |
| qsort=: (($:@(<#[) , (=#[) , $:@(>#[)) ({~ ?@#)) ^: (1<#) | |
| qsortmod=: (($:@(<#[) ; (=#[) ,&< $:@(>#[)) ({~ ?@#)) ^: (1<#) | |
| NB. ^ ^ | |
| NB. | | | |
| NB. change , to ; add &< | |
| NB. Create an array of 30 random numbers between 0 and 9 | |
| v=: 30 ?@$ 10 | |
| echo v | |
| echo qsort v | |
| echo qsortmod v | |
| exit'' |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| $ ./qsort.j | |
| 9 1 1 4 8 3 3 2 5 4 7 1 0 1 9 0 0 8 6 6 3 8 7 2 3 2 5 9 7 4 | |
| 0 0 0 1 1 1 1 2 2 2 3 3 3 3 4 4 4 5 5 6 6 7 7 7 8 8 8 9 9 9 | |
| ┌─────────────────────────────┬───────┬──────────────────────────────────────────────────┐ | |
| │┌─────────┬───────┬─────────┐│3 3 3 3│┌───────────────────────┬─────┬──────────────────┐│ | |
| ││┌┬─────┬┐│1 1 1 1│┌┬─────┬┐││ ││┌┬─────┬──────────────┐│7 7 7│┌┬─────┬─────────┐││ | |
| ││││0 0 0│││ │││2 2 2││││ ││││4 4 4│┌┬───┬───────┐││ │││8 8 8│┌┬─────┬┐│││ | |
| ││└┴─────┴┘│ │└┴─────┴┘││ ││││ │││5 5│┌┬───┬┐│││ │││ │││9 9 9│││││ | |
| │└─────────┴───────┴─────────┘│ ││││ │││ │││6 6│││││ │││ │└┴─────┴┘│││ | |
| │ │ ││││ │││ │└┴───┴┘│││ │└┴─────┴─────────┘││ | |
| │ │ ││││ │└┴───┴───────┘││ │ ││ | |
| │ │ ││└┴─────┴──────────────┘│ │ ││ | |
| │ │ │└───────────────────────┴─────┴──────────────────┘│ | |
| └─────────────────────────────┴───────┴──────────────────────────────────────────────────┘ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment