Built-in Mathematica stuff

Mathematica has built in functions to do searching and sorting.  In fact, you can define your own comparison functions.

big = randomList[10^4, 10^6] ; big//Short

{818887, 944437, 777470, 603967, 870544, 357732, 887677, 32863, 9984, 801299, 976910, 696577, 412405, 132837, 475887, 283260, 550728}

RowBox[{Select[big, Function[x, x<100]],      , RowBox[{(*,   ... ox[{Search,  , for,  , all,  , the,  , elements,  , less,  , than,  , 100.}],   , *)}]}]

{99, 97, 16}

Select[big, #<100&]      (* The same thing using another notation for a function *)

{99, 97, 16}

Select[{1, 2, 3, 5, 8, 12, 20, 12}, Function[x, x11]]     (* Find an element equal to 11 *)

{}

Select[{1, 2, 3, 5, 8, 12, 20, 12}, Function[x, x12], 1]     (* Find the first element equal to 12 *)

{12}

Select[big, Function[x, x<1000]]    (* or something like Function[{x, y, z}, Sin[x y z]] *)

{466, 732, 741, 913, 250, 409, 647, 506, 997, 883, 10, 374}

To find an index, one can use the Position[ ] function.  Here "10" shows up at positions 1 and 5.

Position[{10, 20, 1, 3, 10, 3, 20, 50}, 10]

{{1}, {5}}

And there's also a built in sorting function.   The "Short" is just a way to keep from printing way to much stuff.

? *Sort*

Sort[list] sorts the elements of list into canonical order. Sort[list, p] sorts using the ordering function p. More…

Short[  bigSort = Sort[big]   ]

{16, 97, 99, 143, 318, 416, 524, 530, 710, 890, 987, 9979, 999538, 999586, 999631, 999660, 999669, 999723, 999771, 999806, 999957, 999962}

which can take a function of two arguments.  This one sorts the list into even numbers and odd numbers.

evenAndOdd = Function[{x, y}, EvenQ[x] ∧OddQ[y] ] ;

evenAndOdd[3, 5]

False

evenAndOdd[2, 11]

True

Short[ Sort[big, evenAndOdd] ]

{550728, 283260, 976910, 418644, 125794, 464370, 719564, 438310, 9984, 593237, 864901, 894577, 32863, 887677, 603967, 944437, 818887}

So does this, with a funkier notation.

Short[ Sort[big, EvenQ[#1] ∧OddQ[#2] &] ]

{550728, 283260, 976910, 418644, 125794, 464370, 719564, 438310, 9984, 593237, 864901, 894577, 32863, 887677, 603967, 944437, 818887}


Created by Mathematica  (September 29, 2004)