Python - Sort a list in ascending and descending order without using in-built function and in the most efficient way
This piece of logic goes through a list how our eyes would go though it to sort it in ascending and descending order.
OUTPUT
Ascending Before: [1, 4, 8, 3, 5, 2, 4, 2, 7, 6, 9, 5, 7]
Ascending After: [1, 2, 2, 3, 4, 4, 5, 5, 6, 7, 7, 8, 9]
Descending Before: [1, 2, 2, 3, 4, 4, 5, 5, 6, 7, 7, 8, 9]
Descending After: [9, 8, 7, 7, 6, 5, 5, 4, 4, 3, 2, 2, 1]
class Sorta:
def __init__(self, a):
self.a = a
def sortascend(self):
print("Ascending Before: {}".format(self.a))
index = 1 # to track upto what have we checked
while index < len(self.a): #while runs till index reaches the end of array
if self.a[index] < self.a[index-1]: # if not ascending makes ascending
temp = self.a[index]
self.a[index] = self.a[index-1]
self.a[index-1] = temp
bool1 = True
index2 = index
while bool1: # runs backwards till descending pairs are encountered
index2 -= 1
if self.a[index2] < self.a[index2-1]: # if not ascending makes ascending
temp = self.a[index2]
self.a[index2] = self.a[index2-1]
self.a[index2-1] = temp
else: # else gets out of while loop
bool1 = False
index += 1 # moves to next index
print("Ascending After: {}".format(self.a))
def sortdescend(self):
print("Descending Before: {}".format(self.a))
index = 1 # to track upto what have we checked
while index < len(self.a): #while runs till index reaches the end of array
if self.a[index] > self.a[index-1]: # if not ascending makes ascending
temp = self.a[index]
self.a[index] = self.a[index-1]
self.a[index-1] = temp
bool1 = True
index2 = index
while bool1: # runs backwards till descending pairs are encountered
index2 -= 1
if self.a[index2] > self.a[index2-1] and index2 > 0: # if not ascending makes ascending
temp = self.a[index2]
self.a[index2] = self.a[index2-1]
self.a[index2-1] = temp
else: # else gets out of while loop
bool1 = False
index += 1 # moves to next index
print("Descending After: {}".format(self.a))
a = [1,4,8,3,5,2,4,2,7,6,9,5,7]
obj = Sorta(a)
obj.sortascend()
obj.sortdescend()
Ascending Before: [1, 4, 8, 3, 5, 2, 4, 2, 7, 6, 9, 5, 7]
Ascending After: [1, 2, 2, 3, 4, 4, 5, 5, 6, 7, 7, 8, 9]
Descending Before: [1, 2, 2, 3, 4, 4, 5, 5, 6, 7, 7, 8, 9]
Descending After: [9, 8, 7, 7, 6, 5, 5, 4, 4, 3, 2, 2, 1]
Comments
Post a Comment