Friday, July 17, 2015
Python: sort (3)
Abstract: bitmap sort
bitmap can store huge list with less memory usage. Another application of bitmap is for sort. But a shortage of bitmap sort is no duplicates allowed in a given list.
The result:
Unsorted list: [401, 293, 207, 304, 107, 10, 696, 677, 13, 788]
Sorted list by increasing: [788, 696, 677, 401, 304, 293, 207, 107, 13, 10]
Sorted list by decreasing: [10, 13, 107, 207, 293, 304, 401, 677, 696, 788]
The script:
# -*- coding: utf-8 -*-
"""
Created on Fri Jul 17 11:51:57 2015
@author: yuan
"""
import random
import math
class sort_methods:
def __init__(self, arr):
self.num=len(arr)
self.arr=arr
def to_bitmap(self):
#create bitmap
bitmap_len=int(math.ceil(max(self.arr)/32.))
bitmap=[0]*bitmap_len
for v in self.arr:
divide, remainder = divmod(v, 32)
bitmap[divide]=(2**remainder)+bitmap[divide]
#convert to list
mylist=[]
for i in range(bitmap_len):
bit_str=format(bitmap[i], 'b')[::-1]
#print bit_str
for index, element in enumerate(bit_str):
a=0
if int(element)==1:
a=i*32+index
mylist.append(a)
#print index,element, a
return mylist
def Mysort(self,decreasing=0):
#get bitmap
sorted=self.to_bitmap()
if decreasing ==1:
sorted=sorted[::-1]
return sorted
#####################
#main programm
arr=random.sample(range(1000),10)
print "Unsorted list:", arr
#
S=sort_methods(arr)
#increasing
sorted=S.Mysort(decreasing=1)
print 'Sorted list by increasing:', sorted
#increasing
sorted=S.Mysort(decreasing=0)
print 'Sorted list by decreasing:', sorted
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment