Python Programs With Headings
Python Programs With Headings
Bubble Sorting
Source Code:
def bubble_sort(arr):
n = len(arr)
# Traverse through all array elements
for i in range(n):
# Last i elements are already sorted
for j in range(0, n-i-1):
# Swap if the element found is greater
if arr[j] > arr[j+1]:
arr[j], arr[j+1] = arr[j+1], arr[j]
# Example usage
arr = [64, 34, 25, 12, 22, 11, 90]
print("Original array:", arr)
bubble_sort(arr)
Output Screenshot:
2. Insertion Sorting
Source Code:
def insertion_sort(arr):
# Traverse through 1 to len(arr)
for i in range(1, len(arr)):
key = arr[i]
# Move elements of arr[0...i-1], that are greater than key, to one position ahead
j=i-1
while j >= 0 and key < arr[j]:
arr[j + 1] = arr[j]
j -= 1
arr[j + 1] = key
insertion_sort(arr)
Output Screenshot:
3. Palindrome Check
Source Code:
def is_palindrome(s):
# Converting to lowercase and removing spaces
s = s.replace(" ", "").lower()
# Check if string is equal to its reverse
return s == s[::-1]
if is_palindrome(s):
print(f'"{s}" is a palindrome.')
else:
print(f'"{s}" is not a palindrome.')
Output Screenshot: