Skip to content

Commit 3730aca

Browse files
Added reverse an array, binary search and check palindrome programs
1 parent 62efcb4 commit 3730aca

File tree

3 files changed

+76
-0
lines changed

3 files changed

+76
-0
lines changed

arrayReverse.py

+28
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
# Simple swapping of array elements using two pointer method
2+
3+
def reverse(arr):
4+
start = 0
5+
end = len(arr) - 1
6+
temp = 0
7+
8+
while( start < end ):
9+
temp=arr[start]
10+
arr[start]=arr[end]
11+
arr[end]=temp
12+
start += 1
13+
end -= 1
14+
15+
# User input starts
16+
def userInput():
17+
arr = []
18+
n = int(input("Enter number of elements:"))
19+
print("Enter the elements")
20+
for i in range(0,n):
21+
element = int(input())
22+
arr.append(element)
23+
24+
print("Array before reversing:", arr)
25+
reverse(arr)
26+
print("Array after reversing:", arr)
27+
28+
userInput()

binarySearch.py

+31
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
def binarySearch(arr,target):
2+
start = 0
3+
end = len(arr) - 1
4+
5+
while ( start <= end ):
6+
mid = start + ( end - start ) // 2
7+
if (target < arr[mid]):
8+
end = mid - 1
9+
elif (target > arr[mid]):
10+
start = mid + 1
11+
else:
12+
return mid
13+
return -1
14+
15+
def userInput():
16+
arr = []
17+
n = int(input("Enter number of elements: "))
18+
print("Enter the elements")
19+
for i in range(0,n):
20+
element = int(input())
21+
arr.append(element)
22+
print(arr)
23+
target = int(input("Enter the target element: "))
24+
25+
result = binarySearch(arr,target)
26+
if(result == -1):
27+
print("Element not found")
28+
else:
29+
print("The element was found at index ", result)
30+
31+
userInput()

palindrome.py

+17
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
# Function to check if the number is palindrome or not
2+
3+
def checkPalindrome(check):
4+
palin = 0
5+
rev = check
6+
while( rev > 0):
7+
rem = rev % 10
8+
palin = (palin * 10) + rem
9+
rev //= 10
10+
11+
if check == palin :
12+
print(check, "is a palindrome number :D ")
13+
else:
14+
print("Sorry, " , check , " is not a palindrome number :(")
15+
16+
check = int(input("Please an enter to number :"))
17+
checkPalindrome(check)

0 commit comments

Comments
 (0)