Skip to content

Instantly share code, notes, and snippets.

@adamwespiser
Created December 26, 2012 03:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save adamwespiser/4377692 to your computer and use it in GitHub Desktop.
Save adamwespiser/4377692 to your computer and use it in GitHub Desktop.
attempt at random.shuffle using mergesort with random comparison
# Copyright (c) 2012 the authors listed at the following URL, and/or
# the authors of referenced articles or incorporated external code:
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
# IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
# CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
# SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#
# Retrieved from: http://en.literateprograms.org/Merge_sort_(Python)?oldid=18716
import random
import os
random.seed(os.urandom(1))
def merge(left, right):
result = []
i ,j = 0, 0
while i < len(left) and j < len(right):
#if left[i] <= right[j]:
if random.random() < 0.5 :
result.append(left[i])
i += 1
else:
result.append(right[j])
j += 1
result += left[i:]
result += right[j:]
return result
def mergesort(lst):
if len(lst) <= 1:
return lst
middle = int( len(lst) / 2 )
left = mergesort(lst[:middle])
right = mergesort(lst[middle:])
return merge(left, right)
counts = [0,0,0,0,0,0,0,0,0,0,0,0,0]
if __name__ == "__main__":
z = 0
while(z < 100000):
z = z + 1
x = [0, 4, 8, 3, 6, 7, 4, 2, 1, 9, 4, 5]
y = mergesort(x)
counts[y.index(0)] = counts[y.index(0)] + 1
for i in range(0,9):
print counts[i]
wespiser@home:projects>python mg.py
12694
10731
9706
8976
8452
7833
7611
7423
7063
wespiser@home:projects>python mg.py
12572
10770
9938
9036
8299
7896
7605
7332
6936
wespiser@home:projects>python mg.py
12554
11009
9795
8909
8513
7893
7614
7269
7048
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment