I am looking for a faster, less execution time approach to get maximum and minimum elements of an array of integer, which means we need to sort an array of integers. Without using any inbuilt functions like sort() except range() and len() and using only one for or while loop, which I can't figure out.
def getMinMax( a, n):
while 1 == 1:
run = False
for i in range(n):
if i < (n-1) and a[i] > a[i+1]:
run = True
if run:
for i in range(n):
if i < (n-1) and a[i] > a[i+1]:
temp = a[i]
a[i] = a[i+1]
a[i+1] = temp
else:
break
return a[0], a[i], a
A = [2, 167, 56, 3, 10000, 1]
min_elem, max_elem, sorted_array = getMinMax(A, len(A))
min_elem, max_elem, sorted_array
Output:
(1, 10000, [1, 2, 3, 56, 167, 10000])
With one loop
def getMinMax( a, n):
min_elem = a[0]
max_elem = a[0]
for i in range(n):
if i < (n-1):
if a[i] > a[i+1]:
temp = a[i]
a[i] = a[i+1]
a[i+1] = temp
max_var, min_var = a[n-1], a[0]
return max_elem, min_elem
array = [3,123,200,4,500000,1]
getMinMax( array, len(array))
Output:
(500000, 3)