STEP - 1: Start The Program STEP - 2: Initialize The List
STEP - 1: Start The Program STEP - 2: Initialize The List
b
Implement recursive and non-recursive algorithms and study the order of growth from
log2n to n!.
AIM :
To write a python program to implement Non-Recursive algorithm for
permutation and binary search and studying the order of growth from log2n to
n!.
ALGORITHM – PERMUTATION :
Start with the input list arr in its sorted order to ensure that the
permutations are generated in lexicographical order.
Find the largest index k such that arr[k] < arr[k + 1]. If no such index
exists (k == -1), the current permutation is the last permutation, and
the function returns False.
PSEUDOCODE – PERMUTATION :
Function next_permutation(arr):
k = length of arr - 2
while k >= 0 and arr[k] >= arr[k + 1]:
k = k - 1
if k == -1:
return False
l = length of arr - 1
while arr[k] >= arr[l]:
l = l - 1
Swap arr[k] and arr[l]
Reverse the sequence arr[k + 1:]
return True
Function generate_permutations(arr):
Sort arr
while True:
Print arr
if not next_permutation(arr):
break
arr = [1, 2, 3]
start_time = current time
generate_permutations(arr)
execution_time = current time - start_time
Print "Execution time: ", execution_time
o Set two pointers: left to the beginning of the array (0) and right to the
end of the array (len(arr) - 1).
o Use a while loop to repeatedly narrow down the search range as long
as left is less than or equal to right.
o Calculate the mid index as the average of left and right using the
formula mid = left + (right - left) // 2 to prevent overflow.
o Compare the Middle Element:
If arr[mid] is equal to the target x, return mid since the target is
found.
If arr[mid] is less than x, this means the target must be in the
right half of the array. Thus, move the left pointer to mid + 1.
If arr[mid] is greater than x, this means the target must be in the
left half of the array. Thus, move the right pointer to mid - 1.
o The loop terminates either when the target is found or when the left
pointer surpasses the right pointer, indicating that the element is not
present in the array.
Return -1