In [8]:
def max_val(nums):
mval = nums[0]
for i in nums:
if mval < i:
mval = i
return mval
b = [30, 1, 2, 4, 7, 9]
print max_val(b)
In [6]:
def min_val(nums):
mval = nums[0]
for i in nums:
if mval > i:
mval = i
return mval
b = [30,2,4]
print min_val(b)
In [14]:
a = [1, 10, 4, 5, 6]
a.sort(reverse = True)
a
Out[14]:
In [15]:
def merge_sort(arr, desc = False):
if len(arr) <= 1: return arr # only 2 or more
half = len(arr) // 2 # divide by 2
L = merge_sort(arr[:half], desc) # Left: first half
R = merge_sort(arr[half:], desc) # Right: except first half
mer = [] # array for result
while len(L) > 0 and len(R) > 0:
if (L[0] > R[0] and not desc) or (L[0] < R[0] and desc):
mer.append(R[0]); R.pop(0) # append R[0] and remove
else:
mer.append(L[0]); L.pop(0) # append L[0] and remove
# if out of L or R, append rest
if len(L) > 0: mer += L
if len(R) > 0: mer += R
return mer # return
In [16]:
unsorted = [6, 4, 1, 7, 8, 5, 2, 3]
print(" Unsorted: %s" % unsorted)
print(" Ascending: %s" % merge_sort(unsorted) )
print("Descending: %s" % merge_sort(unsorted, True) )