# # Generates n random strings and then sorts them using bubble sort. # Execute with command: jython bsort.py # Adapted from contribution by Jim Adrig (jim@trampolining.com) # import random import time num = 10 # number of strings to sort ssize = 20 # size of each string. chars = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z' ] array = [] # Do not specify the size on purpose def populate( array, num): for i in range(0, num): s = "" for j in range(0, ssize): r = random.randint( 0, len(chars) - 1 ) s += chars[r] array.append(s) def bsort( array ): n = len(array) for i in range(n-1, 0, -1): for j in range(0, i): if array[j] > array[j+1]: t = array[j] array[j] = array[j+1] array[j+1] = t print "Populating the array with ", num, " Strings, each of ", ssize, " characters ..." st = time.clock() populate(array, num) et = time.clock() print " ... done. Elapsed time: ", (et - st)*1000, " millis." #print "Original Array:", array print "Sorting the array ..." st = time.clock() bsort(array); # array.sort() # Much faster ! et =time.clock() print " ... done. Elapsed time: ", (et - st)*1000, " millis." #print "Sorted Array:", array