Coverage for nltk.misc.sort : 89%
![](keybd_closed.png)
Hot-keys on this page
r m x p toggle line displays
j k next/prev highlighted chunk
0 (zero) top of page
1 (one) first highlighted chunk
# Natural Language Toolkit: List Sorting # # Copyright (C) 2001-2012 NLTK Project # Author: Steven Bird <sb@csse.unimelb.edu.au> # URL: <http://www.nltk.org/> # For license information, see LICENSE.TXT
This module provides a variety of list sorting algorithms, to illustrate the many different algorithms (recipes) for solving a problem, and how to analyze algorithms experimentally. """
# These algorithms are taken from: # Levitin (2004) The Design and Analysis of Algorithms
################################################################## # Selection Sort ##################################################################
""" Selection Sort: scan the list to find its smallest element, then swap it with the first element. The remainder of the list is one element smaller; apply the same method to this list, and so on. """
################################################################## # Bubble Sort ##################################################################
""" Bubble Sort: compare adjacent elements of the list left-to-right, and swap them if they are out of order. After one pass through the list swapping adjacent items, the largest item will be in the rightmost position. The remainder is one element smaller; apply the same method to this list, and so on. """
################################################################## # Merge Sort ##################################################################
else: else:
""" Merge Sort: split the list in half, and sort each half, then combine the sorted halves. """
################################################################## # Quick Sort ##################################################################
################################################################## # Demonstration ##################################################################
from random import shuffle
for size in (10, 20, 50, 100, 200, 500, 1000): a = list(range(size))
# various sort methods shuffle(a); count_selection = selection(a) shuffle(a); count_bubble = bubble(a) shuffle(a); count_merge = merge(a) shuffle(a); count_quick = quick(a)
print((("size=%5d: selection=%8d, bubble=%8d, " "merge=%6d, quick=%6d") % (size, count_selection, count_bubble, count_merge, count_quick)))
demo() |