Advertisement
Guest User

Sort timing for unsorted lists

a guest
Jun 18th, 2015
502
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 26.50 KB | None | 0 0
  1. from collections import defaultdict
  2. import timeit
  3. from heapq import merge
  4. import random
  5. from functools import total_ordering
  6. from bisect import bisect_left
  7. from math import log
  8.  
  9. """ RADIX SORT"""
  10.  
  11. def getDigit(num, base, digit_num):
  12. # pulls the selected digit
  13. return (num // base ** digit_num) % base
  14.  
  15. def makeBlanks(size):
  16. # create a list of empty lists to hold the split by digit
  17. return [ [] for i in range(size) ]
  18.  
  19. def split(a_list, base, digit_num):
  20. buckets = makeBlanks(base)
  21. for num in a_list:
  22. # append the number to the list selected by the digit
  23. buckets[getDigit(num, base, digit_num)].append(num)
  24. return buckets
  25.  
  26. # concatenate the lists back in order for the next step
  27. def rmerge(a_list):
  28. new_list = []
  29. for sublist in a_list:
  30. new_list.extend(sublist)
  31. return new_list
  32.  
  33. def maxAbs(a_list):
  34. # largest abs value element of a list
  35. return max(abs(num) for num in a_list)
  36.  
  37. def split_by_sign(a_list):
  38. # splits values by sign - negative values go to the first bucket,
  39. # non-negative ones into the second
  40. buckets = [[], []]
  41. for num in a_list:
  42. if num < 0:
  43. buckets[0].append(num)
  44. else:
  45. buckets[1].append(num)
  46. return buckets
  47.  
  48. def radix_sort(a_list, base):
  49. # there are as many passes as there are digits in the longest number
  50. passes = int(round(log(maxAbs(a_list), base)) + 1)
  51. new_list = list(a_list)
  52. for digit_num in range(passes):
  53. new_list = rmerge(split(new_list, base, digit_num))
  54. return rmerge(split_by_sign(new_list))
  55.  
  56. """ PATIENCE SORT """
  57.  
  58. @total_ordering
  59. class Pile(list):
  60. def __lt__(self, other): return self[-1] < other[-1]
  61. def __eq__(self, other): return self[-1] == other[-1]
  62.  
  63. def patience_sort(n):
  64. piles = []
  65. # sort into piles
  66. for x in n:
  67. new_pile = Pile([x])
  68. i = bisect_left(piles, new_pile)
  69. if i != len(piles):
  70. piles[i].append(x)
  71. else:
  72. piles.append(new_pile)
  73.  
  74. # use a heap-based merge to merge piles efficiently
  75. n[:] = merge(*[reversed(pile) for pile in piles])
  76. return n
  77.  
  78. """ MERGE SORT """
  79.  
  80. def merge_sort(m):
  81. if len(m) <= 1:
  82. return m
  83.  
  84. middle = len(m) // 2
  85. left = m[:middle]
  86. right = m[middle:]
  87.  
  88. left = merge_sort(left)
  89. right = merge_sort(right)
  90. return list(merge(left, right))
  91.  
  92. """ HEAP SORT """
  93.  
  94. def heap_sort(lst):
  95. ''' Heapsort. Note: this function sorts in-place (it mutates the list). '''
  96.  
  97. # in pseudo-code, heapify only called once, so inline it here
  98. for start in range((len(lst)-2)/2, -1, -1):
  99. siftdown(lst, start, len(lst)-1)
  100.  
  101. for end in range(len(lst)-1, 0, -1):
  102. lst[end], lst[0] = lst[0], lst[end]
  103. siftdown(lst, 0, end - 1)
  104. return lst
  105.  
  106. def siftdown(lst, start, end):
  107. root = start
  108. while True:
  109. child = root * 2 + 1
  110. if child > end: break
  111. if child + 1 <= end and lst[child] < lst[child + 1]:
  112. child += 1
  113. if lst[root] < lst[child]:
  114. lst[root], lst[child] = lst[child], lst[root]
  115. root = child
  116. else:
  117. break
  118.  
  119. """ QUICK SORT """
  120.  
  121. def quick_sort(arr):
  122. less = []
  123. pivotList = []
  124. more = []
  125. if len(arr) <= 1:
  126. return arr
  127. else:
  128. pivot = arr[0]
  129. for i in arr:
  130. if i < pivot:
  131. less.append(i)
  132. elif i > pivot:
  133. more.append(i)
  134. else:
  135. pivotList.append(i)
  136. less = quick_sort(less)
  137. more = quick_sort(more)
  138. return less + pivotList + more
  139.  
  140. """ SIMPLE SORT """
  141.  
  142. def simple_sort(unsorted_set, order):
  143. sorted_list = []
  144. for i in order:
  145. if i in unsorted_set:
  146. sorted_list.append(i)
  147. return sorted_list
  148.  
  149. """ SHELL SORT """
  150.  
  151. def shell_sort(seq):
  152. inc = len(seq) // 2
  153. while inc:
  154. for i, el in enumerate(seq):
  155. while i >= inc and seq[i - inc] > el:
  156. seq[i] = seq[i - inc]
  157. i -= inc
  158. seq[i] = el
  159. inc = 1 if inc == 2 else int(inc * 5.0 / 11)
  160. return seq
  161.  
  162. """ BUBBLE SORT """
  163.  
  164. def bubble_sort(seq):
  165. """Inefficiently sort the mutable sequence (list) in place.
  166. seq MUST BE A MUTABLE SEQUENCE.
  167.  
  168. As with list.sort() and random.shuffle this does NOT return
  169. """
  170. changed = True
  171. while changed:
  172. changed = False
  173. for i in xrange(len(seq) - 1):
  174. if seq[i] > seq[i+1]:
  175. seq[i], seq[i+1] = seq[i+1], seq[i]
  176. changed = True
  177. return seq
  178.  
  179. """ INSERTION SORT """
  180.  
  181. def insertion_sort(l):
  182. for i in xrange(1, len(l)):
  183. j = i-1
  184. key = l[i]
  185. while (l[j] > key) and (j >= 0):
  186. l[j+1] = l[j]
  187. j -= 1
  188. l[j+1] = key
  189. return l
  190.  
  191. """ INSERTION SORT BINARY """
  192.  
  193. def insertion_sort_bin(seq):
  194. for i in range(1, len(seq)):
  195. key = seq[i]
  196. # invariant: ``seq[:i]`` is sorted
  197. # find the least `low' such that ``seq[low]`` is not less then `key'.
  198. # Binary search in sorted sequence ``seq[low:up]``:
  199. low, up = 0, i
  200. while up > low:
  201. middle = (low + up) // 2
  202. if seq[middle] < key:
  203. low = middle + 1
  204. else:
  205. up = middle
  206. # insert key at position ``low``
  207. seq[:] = seq[:low] + [key] + seq[low:i] + seq[i + 1:]
  208. return seq
  209.  
  210. """ CIRCLE SORT """
  211.  
  212. def circle_sort_backend(A=[], L=0, R=0):
  213. '''
  214. >>> L = [3, 2, 8, 28, 2,]
  215. >>> circle_sort(L)
  216. 3
  217. >>> print(L)
  218. [2, 2, 3, 8, 28]
  219. >>> L = [3, 2, 8, 28,]
  220. >>> circle_sort(L)
  221. 1
  222. >>> print(L)
  223. [2, 3, 8, 28]
  224. '''
  225. n = R-L
  226. if n < 2:
  227. return 0
  228. swaps = 0
  229. m = n//2
  230. for i in range(m):
  231. if A[R-(i+1)] < A[L+i]:
  232. (A[R-(i+1)], A[L+i],) = (A[L+i], A[R-(i+1)],)
  233. swaps += 1
  234. if (n & 1) and (A[L+m] < A[L+m-1]):
  235. (A[L+m-1], A[L+m],) = (A[L+m], A[L+m-1],)
  236. swaps += 1
  237. return swaps + circle_sort_backend(A, L, L+m) + circle_sort_backend(A, L+m, R)
  238.  
  239. def circle_sort(L=[]):
  240. swaps = 0
  241. s = 1
  242. while s:
  243. s = circle_sort_backend(L, 0, len(L))
  244. swaps += s
  245. return L
  246.  
  247. """ COCKTAIL SORT """
  248.  
  249. def cocktail_sort(A):
  250. up = range(len(A)-1)
  251. while True:
  252. for indices in (up, reversed(up)):
  253. swapped = False
  254. for i in indices:
  255. if A[i] > A[i+1]:
  256. A[i], A[i+1] = A[i+1], A[i]
  257. swapped = True
  258. if not swapped:
  259. return A
  260.  
  261. """ COUNTING SORT """
  262.  
  263. def counting_sort(array, mn, mx):
  264. count = defaultdict(int)
  265. for i in array:
  266. count[i] += 1
  267. result = []
  268. for j in range(mn,mx+1):
  269. result += [j]* count[j]
  270. return result
  271.  
  272. """ CYCLE SORT """
  273.  
  274. def cycle_sort(vector):
  275. "Sort a vector in place and return the number of writes."
  276. writes = 0
  277.  
  278. # Loop through the vector to find cycles to rotate.
  279. for cycleStart, item in enumerate(vector):
  280.  
  281. # Find where to put the item.
  282. pos = cycleStart
  283. for item2 in vector[cycleStart + 1:]:
  284. if item2 < item:
  285. pos += 1
  286.  
  287. # If the item is already there, this is not a cycle.
  288. if pos == cycleStart:
  289. continue
  290.  
  291. # Otherwise, put the item there or right after any duplicates.
  292. while item == vector[pos]:
  293. pos += 1
  294. vector[pos], item = item, vector[pos]
  295. writes += 1
  296.  
  297. # Rotate the rest of the cycle.
  298. while pos != cycleStart:
  299.  
  300. # Find where to put the item.
  301. pos = cycleStart
  302. for item2 in vector[cycleStart + 1:]:
  303. if item2 < item:
  304. pos += 1
  305.  
  306. # Put the item there or right after any duplicates.
  307. while item == vector[pos]:
  308. pos += 1
  309. vector[pos], item = item, vector[pos]
  310. writes += 1
  311.  
  312. return vector
  313.  
  314. """ GNOME SORT """
  315.  
  316. def gnome_sort(a):
  317. i,j,size = 1,2,len(a)
  318. while i < size:
  319. if a[i-1] <= a[i]:
  320. i,j = j, j+1
  321. else:
  322. a[i-1],a[i] = a[i],a[i-1]
  323. i -= 1
  324. if i == 0:
  325. i,j = j, j+1
  326. return a
  327.  
  328. """ PANCAKE SORT """
  329.  
  330. def pancake_sort(data):
  331. if len(data) <= 1:
  332. return data
  333. for size in range(len(data), 1, -1):
  334. maxindex = max(range(size), key=data.__getitem__)
  335. if maxindex+1 != size:
  336. # This indexed max needs moving
  337. if maxindex != 0:
  338. # Flip the max item to the left
  339. data[:maxindex+1] = reversed(data[:maxindex+1])
  340. # Flip it into its final position
  341. data[:size] = reversed(data[:size])
  342. return data
  343.  
  344. """ SELECTION SORT """
  345.  
  346. def selection_sort(lst):
  347. for i, e in enumerate(lst):
  348. mn = min(range(i,len(lst)), key=lst.__getitem__)
  349. lst[i], lst[mn] = lst[mn], e
  350. return lst
  351.  
  352. """
  353. Binary Search Tree: A sorted collection of values that supports
  354. efficient insertion, deletion, and minimum/maximum value finding.
  355. """
  356. # Copyright (C) 2008 by Edward Loper
  357. #
  358. # Permission is hereby granted, free of charge, to any person obtaining a copy
  359. # of this software and associated documentation files (the "Software"), to deal
  360. # in the Software without restriction, including without limitation the rights
  361. # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  362. # copies of the Software, and to permit persons to whom the Software is
  363. # furnished to do so, subject to the following conditions:
  364. #
  365. # The above copyright notice and this permission notice shall be included in
  366. # all copies or substantial portions of the Software.
  367. #
  368. # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  369. # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  370. # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  371. # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  372. # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  373. # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  374. # THE SOFTWARE.
  375.  
  376.  
  377. # IMPLEMENTATION NOTES:
  378. #
  379. # Internally, we represent tree nodes using Python lists. These lists
  380. # may either be empty (for empty nodes) or may have length four (for
  381. # non-empty nodes). The non-empty nodes contain:
  382. #
  383. # [left_child, right_child, value, sort_key]
  384. #
  385. # Using lists rather than a node class more than doubles the overall
  386. # performance in the benchmarks that I have run.
  387. #
  388. # The sort key is always accessed as node[-1]. This allows us to
  389. # optimize the case where the sort key is identical to the value, by
  390. # encoding such nodes as simply:
  391. #
  392. # [left_child, right_child, value]
  393. #
  394. # The following constants are used to access the pieces of each search
  395. # node. If the constant-binding optimization recipe (which can be
  396. # downloaded from <http://code.activestate.com/recipes/277940/>) is
  397. # available, then it is used to replace these constants at
  398. # import-time, increasing the binary search tree efficiency by 3-5%.
  399. _LEFT = 0
  400. _RIGHT = 1
  401. _VALUE = 2
  402. _SORT_KEY = -1
  403.  
  404. class BinarySearchTree(object):
  405. """
  406. A sorted collection of values that supports efficient insertion,
  407. deletion, and minimum/maximum value finding. Values may sorted
  408. either based on their own value, or based on a key value whose
  409. value is computed by a key function (specified as an argument to
  410. the constructor).
  411.  
  412. BinarySearchTree allows duplicates -- i.e., a BinarySearchTree may
  413. contain multiple values that are equal to one another (or multiple
  414. values with the same key). The ordering of equal values, or
  415. values with equal keys, is undefined.
  416. """
  417. def __init__(self, sort_key=None):
  418. """
  419. Create a new empty BST. If a sort key is specified, then it
  420. will be used to define the sort order for the BST. If an
  421. explicit sort key is not specified, then each value is
  422. considered its own sort key.
  423. """
  424. self._root = [] # = empty node
  425. self._sort_key = sort_key
  426. self._len = 0 # keep track of how many items we contain.
  427.  
  428. #/////////////////////////////////////////////////////////////////
  429. # Public Methods
  430. #/////////////////////////////////////////////////////////////////
  431.  
  432. def insert(self, value):
  433. """
  434. Insert the specified value into the BST.
  435. """
  436. # Get the sort key for this value.
  437. if self._sort_key is None:
  438. sort_key = value
  439. else:
  440. sort_key = self._sort_key(value)
  441. # Walk down the tree until we find an empty node.
  442. node = self._root
  443. while node:
  444. if sort_key < node[_SORT_KEY]:
  445. node = node[_LEFT]
  446. else:
  447. node = node[_RIGHT]
  448. # Put the value in the empty node.
  449. if sort_key is value:
  450. node[:] = [[], [], value]
  451. else:
  452. node[:] = [[], [], value, sort_key]
  453. self._len += 1
  454.  
  455. def minimum(self):
  456. """
  457. Return the value with the minimum sort key. If multiple
  458. values have the same (minimum) sort key, then it is undefined
  459. which one will be returned.
  460. """
  461. return self._extreme_node(_LEFT)[_VALUE]
  462.  
  463. def maximum(self):
  464. """
  465. Return the value with the maximum sort key. If multiple values
  466. have the same (maximum) sort key, then it is undefined which one
  467. will be returned.
  468. """
  469. return self._extreme_node(_RIGHT)[_VALUE]
  470.  
  471. def find(self, sort_key):
  472. """
  473. Find a value with the given sort key, and return it. If no such
  474. value is found, then raise a KeyError.
  475. """
  476. return self._find(sort_key)[_VALUE]
  477.  
  478. def pop_min(self):
  479. """
  480. Return the value with the minimum sort key, and remove that value
  481. from the BST. If multiple values have the same (minimum) sort key,
  482. then it is undefined which one will be returned.
  483. """
  484. return self._pop_node(self._extreme_node(_LEFT))
  485.  
  486. def pop_max(self):
  487. """
  488. Return the value with the maximum sort key, and remove that value
  489. from the BST. If multiple values have the same (maximum) sort key,
  490. then it is undefined which one will be returned.
  491. """
  492. return self._pop_node(self._extreme_node(_RIGHT))
  493.  
  494. def pop(self, sort_key):
  495. """
  496. Find a value with the given sort key, remove it from the BST, and
  497. return it. If multiple values have the same sort key, then it is
  498. undefined which one will be returned. If no value has the
  499. specified sort key, then raise a KeyError.
  500. """
  501. return self._pop_node(self._find(sort_key))
  502.  
  503. def values(self, reverse=False):
  504. """Generate the values in this BST in sorted order."""
  505. if reverse:
  506. return self._iter(_RIGHT, _LEFT)
  507. else:
  508. return self._iter(_LEFT, _RIGHT)
  509. __iter__ = values
  510.  
  511. def __len__(self):
  512. """Return the number of items in this BST"""
  513. return self._len
  514.  
  515. def __nonzero__(self):
  516. """Return true if this BST is not empty"""
  517. return self._len>0
  518.  
  519. def __repr__(self):
  520. return '<BST: (%s)>' % ', '.join('%r' % v for v in self)
  521.  
  522. def __str__(self):
  523. return self.pprint()
  524.  
  525. def pprint(self, max_depth=10, frame=True, show_key=True):
  526. """
  527. Return a pretty-printed string representation of this binary
  528. search tree.
  529. """
  530. t,m,b = self._pprint(self._root, max_depth, show_key)
  531. lines = t+[m]+b
  532. if frame:
  533. width = max(40, max(len(line) for line in lines))
  534. s = '+-'+'MIN'.rjust(width, '-')+'-+\n'
  535. s += ''.join('| %s |\n' % line.ljust(width) for line in lines)
  536. s += '+-'+'MAX'.rjust(width, '-')+'-+\n'
  537. return s
  538. else:
  539. return '\n'.join(lines)
  540.  
  541. #/////////////////////////////////////////////////////////////////
  542. # Private Helper Methods
  543. #/////////////////////////////////////////////////////////////////
  544.  
  545. def _extreme_node(self, side):
  546. """
  547. Return the leaf node found by descending the given side of the
  548. BST (either _LEFT or _RIGHT).
  549. """
  550. if not self._root:
  551. raise IndexError('Empty Binary Search Tree!')
  552. node = self._root
  553. # Walk down the specified side of the tree.
  554. while node[side]:
  555. node = node[side]
  556. return node
  557.  
  558. def _find(self, sort_key):
  559. """
  560. Return a node with the given sort key, or raise KeyError if not found.
  561. """
  562. node = self._root
  563. while node:
  564. node_key = node[_SORT_KEY]
  565. if sort_key < node_key:
  566. node = node[_LEFT]
  567. elif sort_key > node_key:
  568. node = node[_RIGHT]
  569. else:
  570. return node
  571. raise KeyError("Key %r not found in BST" % sort_key)
  572.  
  573. def _pop_node(self, node):
  574. """
  575. Delete the given node, and return its value.
  576. """
  577. value = node[_VALUE]
  578. if node[_LEFT]:
  579. if node[_RIGHT]:
  580. # This node has a left child and a right child; find
  581. # the node's successor, and replace the node's value
  582. # with its successor's value. Then replace the
  583. # sucessor with its right child (the sucessor is
  584. # guaranteed not to have a left child). Note: node
  585. # and successor may not be the same length (3 vs 4)
  586. # because of the key-equal-to-value optimization; so
  587. # we have to be a little careful here.
  588. successor = node[_RIGHT]
  589. while successor[_LEFT]: successor = successor[_LEFT]
  590. node[2:] = successor[2:] # copy value & key
  591. successor[:] = successor[_RIGHT]
  592. else:
  593. # This node has a left child only; replace it with
  594. # that child.
  595. node[:] = node[_LEFT]
  596. else:
  597. if node[_RIGHT]:
  598. # This node has a right child only; replace it with
  599. # that child.
  600. node[:] = node[_RIGHT]
  601. else:
  602. # This node has no children; make it empty.
  603. del node[:]
  604. self._len -= 1
  605. return value
  606.  
  607. def _iter(self, pre, post):
  608. # Helper for sorted iterators.
  609. # - If (pre,post) = (_LEFT,_RIGHT), then this will generate items
  610. # in sorted order.
  611. # - If (pre,post) = (_RIGHT,_LEFT), then this will generate items
  612. # in reverse-sorted order.
  613. # We use an iterative implemenation (rather than the recursive one)
  614. # for efficiency.
  615. stack = []
  616. node = self._root
  617. while stack or node:
  618. if node: # descending the tree
  619. stack.append(node)
  620. node = node[pre]
  621. else: # ascending the tree
  622. node = stack.pop()
  623. yield node[_VALUE]
  624. node = node[post]
  625.  
  626. def _pprint(self, node, max_depth, show_key, spacer=2):
  627. """
  628. Returns a (top_lines, mid_line, bot_lines) tuple,
  629. """
  630. if max_depth == 0:
  631. return ([], '- ...', [])
  632. elif not node:
  633. return ([], '- EMPTY', [])
  634. else:
  635. top_lines = []
  636. bot_lines = []
  637. mid_line = '-%r' % node[_VALUE]
  638. if len(node) > 3: mid_line += ' (key=%r)' % node[_SORT_KEY]
  639. if node[_LEFT]:
  640. t,m,b = self._pprint(node[_LEFT], max_depth-1,
  641. show_key, spacer)
  642. indent = ' '*(len(b)+spacer)
  643. top_lines += [indent+' '+line for line in t]
  644. top_lines.append(indent+'/'+m)
  645. top_lines += [' '*(len(b)-i+spacer-1)+'/'+' '*(i+1)+line
  646. for (i, line) in enumerate(b)]
  647. if node[_RIGHT]:
  648. t,m,b = self._pprint(node[_RIGHT], max_depth-1,
  649. show_key, spacer)
  650. indent = ' '*(len(t)+spacer)
  651. bot_lines += [' '*(i+spacer)+'\\'+' '*(len(t)-i)+line
  652. for (i, line) in enumerate(t)]
  653. bot_lines.append(indent+'\\'+m)
  654. bot_lines += [indent+' '+line for line in b]
  655. return (top_lines, mid_line, bot_lines)
  656.  
  657. """ AN ABSTRACTION OF TREE SORT """
  658.  
  659. def abstract_tree_sort(unsorted, BinarySearchTree):
  660. tree = BinarySearchTree()
  661. for i in unsorted:
  662. tree.insert(i)
  663. return [i for i in tree]
  664.  
  665. # 'times' is how many repetitions each algorithm should run
  666. times = 100
  667. # 'unique_items' is the number of non-redundant items in the unsorted list
  668. unique_items = 1003
  669. # 'order' is an ordered list
  670. order = []
  671. for number in range(unique_items):
  672. order.append(number)
  673. # Generate the unsorted list
  674. random_list = order[:]
  675. random.shuffle(random_list)
  676. # 'random_set' is used for simple_sort
  677. random_simple = random_list[:]
  678. random_set = {item for item in random_simple}
  679.  
  680. # A list of all sorted lists for each algorithm
  681. sorted_lists = [
  682. simple_sort(random_set, order),
  683. quick_sort(random_list[:]),
  684. merge_sort(random_list[:]),
  685. shell_sort(random_list[:]),
  686. bubble_sort(random_list[:]),
  687. heap_sort(random_list[:]),
  688. insertion_sort(random_list[:]),
  689. insertion_sort_bin(random_list[:]),
  690. circle_sort(random_list[:]),
  691. cocktail_sort(random_list[:]),
  692. counting_sort(random_list[:], 0, unique_items),
  693. cycle_sort(random_list[:]),
  694. gnome_sort(random_list[:]),
  695. pancake_sort(random_list[:]),
  696. patience_sort(random_list[:]),
  697. radix_sort(random_list[:], unique_items),
  698. selection_sort(random_list[:]),
  699. abstract_tree_sort(random_list[:], BinarySearchTree),
  700. sorted(random_list[:])
  701. ]
  702.  
  703. # A set of all sorted lists for each algorithm
  704. sorted_set = {repr(item) for item in sorted_lists}
  705. # If only one version of the sorted list exists, True is evaluated
  706. print 'All algorithms sort identically', len(sorted_set) is 1
  707.  
  708. # Sort slices of an unsorted list and record the times in 'time_record'
  709. time_record = defaultdict(list)
  710. for length in range(2, unique_items, 10):
  711. unsorted = random_list[:length]
  712. # 'unsorted_set' is used for simple_sort
  713. simple_unsorted = unsorted[:]
  714. unsorted_set = {item for item in simple_unsorted}
  715.  
  716. print '**********', length, '**********'
  717.  
  718. print 'simple'
  719. simple = timeit.timeit(lambda: simple_sort(unsorted_set, order), number=times)
  720. time_record['Simple Sort'].append(simple)
  721.  
  722. print 'quick'
  723. quick_unsorted = unsorted[:]
  724. quick = timeit.timeit(lambda: quick_sort(quick_unsorted), number=times)
  725. time_record['Quick Sort'].append(quick)
  726.  
  727. print 'merge'
  728. merge_unsorted = unsorted[:]
  729. merged = timeit.timeit(lambda: merge_sort(merge_unsorted), number=times)
  730. time_record['Merge Sort'].append(merged)
  731.  
  732. print 'shell'
  733. shell_unsorted = unsorted[:]
  734. shell = timeit.timeit(lambda: merge_sort(shell_unsorted), number=times)
  735. time_record['Shell Sort'].append(shell)
  736.  
  737. print 'bubble'
  738. bubble_unsorted = unsorted[:]
  739. bubble = timeit.timeit(lambda: bubble_sort(bubble_unsorted), number=times)
  740. time_record['In Place Bubble Sort'].append(bubble)
  741.  
  742. print 'heap'
  743. heap_unsorted = unsorted[:]
  744. heap = timeit.timeit(lambda: heap_sort(heap_unsorted), number=times)
  745. time_record['In Place Heap Sort'].append(heap)
  746.  
  747. print 'insertion'
  748. insertion_unsorted = unsorted[:]
  749. insertion = timeit.timeit(lambda: insertion_sort(insertion_unsorted), number=times)
  750. time_record['In Place Insertion Sort'].append(insertion)
  751.  
  752. print 'insertion binary'
  753. insertion_bin_unsorted = unsorted[:]
  754. insertion_bin = timeit.timeit(lambda: insertion_sort_bin(insertion_bin_unsorted), number=times)
  755. time_record['In Place Insertion Sort Binary'].append(insertion_bin)
  756.  
  757. print 'circle'
  758. circle_unsorted = unsorted[:]
  759. circle = timeit.timeit(lambda: circle_sort(circle_unsorted), number=times)
  760. time_record['In Place Circle Sort'].append(circle)
  761.  
  762. print 'cocktail'
  763. cocktail_unsorted = unsorted[:]
  764. cocktail = timeit.timeit(lambda: cocktail_sort(cocktail_unsorted), number=times)
  765. time_record['In Place Cocktail Sort'].append(cocktail)
  766.  
  767. print 'counting'
  768. counting_unsorted = unsorted[:]
  769. counting = timeit.timeit(lambda: counting_sort(counting_unsorted, 0, length), number=times)
  770. time_record['Counting Sort'].append(counting)
  771.  
  772. print 'cycle'
  773. cycle_unsorted = unsorted[:]
  774. cycle = timeit.timeit(lambda: cycle_sort(cycle_unsorted), number=times)
  775. time_record['In Place Cycle Sort'].append(cycle)
  776.  
  777. print 'gnome'
  778. gnome_unsorted = unsorted[:]
  779. gnome = timeit.timeit(lambda: gnome_sort(gnome_unsorted), number=times)
  780. time_record['Gnome Sort'].append(gnome)
  781.  
  782. print 'pancake'
  783. pancake_unsorted = unsorted[:]
  784. pancake = timeit.timeit(lambda: pancake_sort(pancake_unsorted), number=times)
  785. time_record['In Place Pancake Sort'].append(pancake)
  786.  
  787. print 'patience'
  788. patience_unsorted = unsorted[:]
  789. patience = timeit.timeit(lambda: patience_sort(patience_unsorted), number=times)
  790. time_record['In Place Patience Sort'].append(patience)
  791.  
  792. print 'radix'
  793. radix_unsorted = unsorted[:]
  794. radix = timeit.timeit(lambda: radix_sort(radix_unsorted, length), number=times)
  795. time_record['Radix Sort'].append(radix)
  796.  
  797. print 'selection'
  798. selection_unsorted = unsorted[:]
  799. selection = timeit.timeit(lambda: selection_sort(selection_unsorted), number=times)
  800. time_record['Selection Sort'].append(selection)
  801.  
  802. print 'tree'
  803. tree_unsorted = unsorted[:]
  804. tree_sorted = timeit.timeit(lambda: abstract_tree_sort(tree_unsorted, BinarySearchTree), number=times)
  805. time_record['Abstract Tree Sort'].append(tree_sorted)
  806.  
  807. print 'tim in c'
  808. tim_unsorted = unsorted[:]
  809. tim = timeit.timeit(lambda: sorted(tim_unsorted), number=times)
  810. time_record['Tim in C'].append(tim)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement