#SortD - JGMiner - April 8, 2014 # a python optimized version of Knuth's Sort D demo # parses ip address by useing Py's native for each char in a string # then uses except catch on try if int to detect the dots # of course you could just use split. def parseIpId(s): a=[0] for i in s: try : a[-1]=10*a[-1]+int(i) except : a.append(0) return a print parseIpId("192.162.36.1") print "Sorting algorithm D page 78, Knuth" def recKey(Rec): return Rec/10 # simple key for integers of 10 : divide by 10 making key domain one tenth record domain # ------------ Data Structures --------------------------- Recs = [10, 10, 30, 50, 70, 90, 20, 40, 40, 60, 0, 100, 100, 40, 30, 40] print " Records: ", Recs Keys = [recKey(i) for i in Recs] # Define a set of keys using a method for repeatability/reuse print " Keys: ", Keys Sorted = [0,]*len(Recs) # Clear a new array for sorted, needs to be fully defined due to random placement of results # ------------ Algorithm --------------------------------- counts = [0,]*len(Keys) # zero a counts array print " D1: counts:", counts for key in Keys: counts[key]+=1 # use each value in K as an index to counts print " D2 & D3: counts:", counts for key in range(min(Keys),max(Keys)): counts[key+1] += counts[(key)] # sum the counts by key value order print " D4: counst:", counts for idx, rec in enumerate(reversed(Recs)): # Using records in reverse order allows the summed counts dictate sorted order key=recKey(rec) # calc key Sorted[counts[key]-1] = rec # need to offset by 1 because its is a true count being used as an index counts[key] -= 1 print " D5 & D6: S:", Sorted
Run
Reset
Share
Import
Link
Embed
Language▼
English
中文
Python Fiddle
Python Cloud IDE
Follow @python_fiddle
Browser Version Not Supported
Due to Python Fiddle's reliance on advanced JavaScript techniques, older browsers might have problems running it correctly. Please download the latest version of your favourite browser.
Chrome 10+
Firefox 4+
Safari 5+
IE 10+
Let me try anyway!
url:
Go
Python Snippet
Stackoverflow Question