keypoints:
1. Double nested loops
2. Compare two neighboring elements at a time
The script:
#sort
class sort_methods:
def __init__(self, arr):
self.pool=arr
self.sorted=list(arr)
self.num=len(arr)
self.index=range(self.num) #update the index based on the index of self.pool
def bubble_sort(self):
last=self.num #the lastest position with replacement
for i in range(self.num): #travel all elements
flag=1
for j in range(1,last):#exchange each other or not
if self.sorted[j-1] > self.sorted[j]:
self.sorted[j-1],self.sorted[j] = self.sorted[j],self.sorted[j-1]
self.index[j-1],self.index[j] = self.index[j],self.index[j-1]
last=j
flag=0
if flag==1:
break
#
return
def my_sort(self, decreasing=0):
#sort
self.bubble_sort()
#decreasing sort
if decreasing==1:
self.sorted.reverse()
#export
print "Unsorted data: ", self.pool
print "Sorted data: ", self.sorted
return self.sorted
#####################
#main programm
arr=random.sample(range(1000),10)
S=sort_methods(arr)
#increasing
sorted=S.my_sort(decreasing=0)
No comments:
Post a Comment