Home Accessibility Courses Twitter The Mouth Facebook Resources Site Map About Us Contact
 
For 2021 - online Python 3 training - see ((here)).

Our plans were to retire in summer 2020 and see the world, but Coronavirus has lead us into a lot of lockdown programming in Python 3 and PHP 7.
We can now offer tailored online training - small groups, real tutors - works really well for groups of 4 to 14 delegates. Anywhere in the world; course language English.

Please ask about private 'maintenance' training for Python 2, Tcl, Perl, PHP, Lua, etc.
Sorting - naturally, or into a different order

There's a natural sort order for many things - for numbers, it's ascending, for words it's a dictionary order, for names it's by surname. But sometimes you want to sort a list of things different, or there's no provided way within a programming language to apply the natural sort to your type of thing.

In PHP, I can sort a list (OK - it's known as an "array") in its natural order:
  $vals = array(4,3,5,6,4,3,2,1,2,5,10,22,11);
  sort($vals);
  print (implode(", ",$vals));

and that will give me the following result:
  1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 10, 11, 22
which is all well and good ... until I tell you that the numbers are the numbers of houses on a busy street where I need to make deliveries, and so I'll need to go up the odd numbers, cross the street once, then go back down the even numbers.

The "trick" is to tell the sort routine how to distinguish between two values applying your criteria - how to tell whether "x" comes before "y" where "x" might be 4 and "y" might be 10. You do this by changing the sort function call to a usort function call, and passing into the function - as a second parameter - the name of a function that you have written that takes two values as parameters, and returns a negative (first input is correctly first), positive (first input should be second when sorted) or zero (same value as far as sort is concerned). This function is the called internally - many times - by the usort routine.

Let's see an example - in this first case, I'm sorting the numbers by their remainder when I divide them by 5 - so it's multiples of 5 first, then numbers that give a remainder of 1, and so on ...
  function remfive($x, $y) {
    return ($x%5 - $y%5);
    }
  $vals = array(4,3,5,6,4,3,2,1,2,5,10,22,11);
  usort($vals,remfive);
  print (implode(", ",$vals));

and that will give me the following result:
  5, 10, 5, 1, 6, 11, 2, 22, 2, 3, 3, 4, 4

With the case of my "postman" sort, all I need is a few more lines in my sort function. Comparing two letters, I first check if they're on opposite sides of the road. If they are, then, I can return a -1 or +1 straight away without comparing the numberic values. Having established that two letters are on the same side of the road, I can then compare the numeric values and sort ascending (odd side) or descending (even side). So my sort routine looks like this:
  function postman($x, $y) {
    if (($x % 2) == 0 and ($y % 2) != 0) return 1;
    if (($x % 2) != 0 and ($y % 2) == 0) return -1;
    if (($x % 2) != 0) return ($x - $y);
    return ($y - $x);
    }

and that will give me the following result:
  1, 3, 3, 5, 5, 11, 22, 10, 6, 4, 4, 2, 2

There's a complete example of this from the learning to program in PHP course that I ran last week ... see source code [here]. The same principle applies in Python - indeed, you can see a very old forum post of mine [here], and an example from the Python course that sorts by the 7th field on a line [here].


If you're wanting to do a user sort in Perl - again - the principle is similar. However, you do NOT pass in the two values to be compared as parameters to your sub - they are passed in via global variables $a and $b instead. There are examples [here] and [here] ... with the default (natural order) control case in a further examples [here]. As there are always many ways in Perl, you can also use an "anonymous block" rather that a sub - see [here]. ((Yes - we do offer public Perl courses if you need to learn Perl!))

In Java you can (re)define the natural sort order yourself on you own class of objects - using the Comparable interface. In this case, you define a method called compareTo which runs on one object, taking another as a parameter, and returns a negative, zero or positive int result. Example [here]. There's an alternative using a comparator class - see [here] and [here] for the two classes needed in this case; you'll want to use this latter method if you need to sort the same data type in more than one different way.
(written 2010-08-14, updated 2010-08-20)

 
Associated topics are indexed as below, or enter http://melksh.am/nnnn for individual articles
Y111 - Python - More on Collections and Sequences
  [61] Python is a fabulous language - (2004-09-24)
  [386] What is a callback? - (2005-07-22)
  [633] Copying a reference, or cloning - (2006-03-05)
  [899] Python - extend v append on a list - (2006-10-20)
  [1304] Last elements in a Perl or Python list - (2007-08-16)
  [1310] Callbacks - a more complex code sandwich - (2007-08-19)
  [1869] Anonymous functions (lambdas) and map in Python - (2008-11-04)
  [1873] List Comprehensions in Python - (2008-11-06)
  [2718] Python - access to variables in the outer scope - (2010-04-12)
  [2894] Sorting people by their names - (2010-07-29)
  [2996] Copying - duplicating data, or just adding a name? Perl and Python compared - (2010-10-12)
  [3150] Python dictionaries - mutable and immutable keys and values - (2011-01-29)
  [3348] List slices in Python - 2 and 3 values forms, with an uplifting example - (2011-07-06)
  [3439] Python for loops - applying a temporary second name to the same object - (2011-09-14)
  [3797] zip in Python - (2012-07-05)
  [4398] Accessing variables across subroutine boundaries - Perl, Python, Java and Tcl - (2015-01-18)
  [4442] Mutable v Immuatble objects in Python, and the implication - (2015-02-24)

P211 - Perl - Hashes
  [240] Conventional restraints removed - (2005-03-09)
  [738] (Perl) Callbacks - what are they? - (2006-05-30)
  [930] -> , >= and => in Perl - (2006-11-18)
  [968] Perl - a list or a hash? - (2006-12-06)
  [1334] Stable sorting - Tcl, Perl and others - (2007-09-06)
  [1705] Environment variables in Perl / use Env - (2008-07-11)
  [1826] Perl - Subs, Chop v Chomp, => v , - (2008-10-08)
  [1856] A few of my favourite things - (2008-10-26)
  [1917] Out of memory during array extend - Perl - (2008-12-02)
  [2833] Fresh Perl Teaching Examples - part 2 of 3 - (2010-06-27)
  [2836] Perl - the duplicate key problem explained, and solutions offered - (2010-06-28)
  [2915] Looking up a value by key - associative arrays / Hashes / Dictionaries - (2010-08-11)
  [3042] Least Common Ancestor - what is it, and a Least Common Ancestor algorithm implemented in Perl - (2010-11-11)
  [3072] Finding elements common to many lists / arrays - (2010-11-26)
  [3106] Buckets - (2010-12-26)
  [3400] $ is atomic and % and @ are molecular - Perl - (2011-08-20)
  [3451] Why would you want to use a Perl hash? - (2011-09-20)
  [3662] Finding all the unique lines in a file, using Python or Perl - (2012-03-20)

J714 - Java - Fundamental classes
  [42] Do languages change? - (2004-09-08)
  [1062] Java sorting - comparable v comparator - (2007-02-02)
  [1502] Java, sorting, ArrayList example, generics - (2008-01-11)
  [1910] Java - Generics - (2008-11-27)
  [2323] Java Collection Objects in the java.util package - (2009-08-05)
  [2418] Viv.java uses unchecked or unsafe operations - explanation and cure - (2009-09-24)
  [2421] Sorting Collections of Objects in Java - (2009-09-25)
  [2649] Length, size or capacity in Java? - (2010-02-24)
  [2734] for and foreach in Java - (2010-04-22)
  [3048] String handling - from first steps to practical examples - (2010-11-13)
  [4330] Java - factory method, encapsulation, hashmap example - (2014-11-27)
  [4396] Java Utility class - flexible replacement for array. Also cacheing in objects and multiple catch clauses example. - (2015-01-16)
  [4421] How healthy are the stars of stage and screen? - (2015-02-09)
  [4431] A Java servlet that is also a stand alone program. And a server that is also a web client. - (2015-02-19)

H106 - PHP - Arrays
  [409] Functions and commands with dangerous names - (2005-08-11)
  [603] PHP - setting sort order with an associative array - (2006-02-13)
  [773] Breaking bread - (2006-06-22)
  [832] Displaying data at 5 items per line on a web page - (2006-08-14)
  [1116] PHP adding arrays / summing arrays - (2007-03-23)
  [1199] Testing for one of a list of values. - (2007-05-22)
  [1451] More PHP sample and demonstration programs - (2007-12-01)
  [1614] When an array is not an array - (2008-04-17)
  [2215] If nothing, make it nothing. - (2009-06-02)
  [2274] PHP preg functions - examples and comparision - (2009-07-08)
  [3004] Increment operators for counting - Perl, PHP, C and others - (2010-10-18)
  [3379] Sorting data the way YOU want it sorted - (2011-08-05)
  [3534] Learning to program in PHP - Regular Expression and Associative Array examples - (2011-12-01)
  [4068] Arrays in PHP - contain different and even mixed data types - (2013-04-24)
  [4072] Splitting the difference with PHP - (2013-04-27)
  [4244] Disambiguation - PHP List - (2014-03-07)


Back to
London to Calne, Corsham, Melksham, Bradford-on-Avon, Chippenham by public Transport
Previous and next
or
Horse's mouth home
Forward to
Does copying a variable duplicate the contents?
Some other Articles
Job applicants - wondering why they apply
Fresh air and beautiful places in Wiltshire
Getting the OO design write - with PHP a example
Does copying a variable duplicate the contents?
Sorting - naturally, or into a different order
London to Calne, Corsham, Melksham, Bradford-on-Avon, Chippenham by public Transport
Downloading a report from the web for further local analysis
Upload Image, Store in database, redisplay in browser. PHP and MySQL
Testing the robustness of our hotel and training systems - holiday and sickness times
4759 posts, page by page
Link to page ... 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96 at 50 posts per page


This is a page archived from The Horse's Mouth at http://www.wellho.net/horse/ - the diary and writings of Graham Ellis. Every attempt was made to provide current information at the time the page was written, but things do move forward in our business - new software releases, price changes, new techniques. Please check back via our main site for current courses, prices, versions, etc - any mention of a price in "The Horse's Mouth" cannot be taken as an offer to supply at that price.

Link to Ezine home page (for reading).
Link to Blogging home page (to add comments).

You can Add a comment or ranking to this page

© WELL HOUSE CONSULTANTS LTD., 2021: 48 Spa Road • Melksham, Wiltshire • United Kingdom • SN12 7NY
PH: 01144 1225 708225 • EMAIL: info@wellho.net • WEB: http://www.wellho.net • SKYPE: wellho

PAGE: http://www.wellho.net/mouth/2920_Sor ... order.html • PAGE BUILT: Sun Oct 11 16:07:41 2020 • BUILD SYSTEM: JelliaJamb