Posts

Showing posts with the label sort

Sort Python dictionaries by key

Sort Python dictionaries by key Even though dictionaries in Python are unordered, we can use this following technique to sort the dictionaries: >>> import collections >>> d = {2:3, 1:89, 4:5, 3:0} >>> od = collections.OrderedDict(sorted(d.items())) >>> od OrderedDict([(1, 89), (2, 3), (3, 0), (4, 5)]) And the best thing is we can still using that collection just like our old dictionary: >> od[1] 89 >>> for k, v in od.iteritems(): print k, v 1  89 2  3 3  0 4  5 Note: the only difference is that we use iteritems() instead of items(). But it will be the same in python 3 (items()) References:  http://stackoverflow.com/questions/9001509/how-can-i-sort-a-dictionary-by-key http://me.dangtrinh.com download file now

Sort Algorithms

Image
Sort Algorithms A major part of computation is sorting data. Sorting allows to identify duplicates and makes data searching more efficient. Selection Sort One of the simplest sorting algorithms is the selection sort algorithm. Its method of finding an element can be somewhat categorized as brute-forcing and so its efficiency is far from its main characteristics. Selection sort goes through an array of elements (say integers) until it finds the smallest one. It then exchanges this smallest integer and it exchanges it with the first integer in the array. After this, it goes through the array again and it looks again for the smallest integer. After finding it, it exchanges it with the second integer in the array. It continues this process until the array is finally sorted. The name of this sorting algorithm is called so because it repeatedly selects  the smallest element every time it goes through the array. Here is a simple example: Taking a look at the pseud...