Skip to content

Instantly share code, notes, and snippets.

@v64
Created March 8, 2018 10:02
Show Gist options
  • Select an option

  • Save v64/74f9d9d726c0fd9399f29ed4862cf8de to your computer and use it in GitHub Desktop.

Select an option

Save v64/74f9d9d726c0fd9399f29ed4862cf8de to your computer and use it in GitHub Desktop.
Quicksort in J
#!/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''
$ ./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