1. Implement Selection Sort:
def selection_sort(arr):
n = len(arr)
for i in range(n):
min_idx = i
for j in range(i + 1, n):
if arr[j] < arr[min_idx]:
min_idx = j
arr[i], arr[min_idx] = arr[min_idx], arr[i]
arr = [64, 25, 12, 22, 11]
selection_sort(arr)
print("Sorted array:", arr)
2. Find the Greatest Among Three Numbers:
a = float(input("Enter the first number: "))
b = float(input("Enter the second number: "))
c = float(input("Enter the third number: "))
max_num = max(a, b, c)
print("Greatest number:", max_num)
3. Implement Insertion Sort:
def insertion_sort(arr):
for i in range(1, len(arr)):
key = arr[i]
j = i - 1
while j >= 0 and key < arr[j]:
arr[j + 1] = arr[j]
j -= 1
arr[j + 1] = key
arr = [12, 11, 13, 5, 6]
insertion_sort(arr)
print("Sorted array:", arr)
4. Convert Decimal to Binary:
dec = int(input("Enter a decimal number: "))
binary = bin(dec)
print("Binary:", binary[2:])
5. Convert Decimal to Octal:
dec = int(input("Enter a decimal number: "))
octal = oct(dec)
print("Octal:", octal[2:])
6. Convert Decimal to Hexadecimal:
dec = int(input("Enter a decimal number: "))
hexadecimal = hex(dec)
print("Hexadecimal:", hexadecimal[2:])
7. Implement a Bubble Sort Algorithm:
def bubble_sort(arr):
n = len(arr)
for i in range(n - 1):
for j in range(0, n - i - 1):
if arr[j] > arr[j + 1]:
arr[j], arr[j + 1] = arr[j + 1], arr[j]
arr = [64, 34, 25, 12, 22, 11, 90]
bubble_sort(arr)
print("Sorted array:", arr)
8. Find the LCM and GCD of Two Numbers:
def compute_lcm(x, y):
lcm = (x * y) // compute_gcd(x, y)
return lcm
def compute_gcd(x, y):
while y:
x, y = y, x % y
return x
num1 = int(input("Enter first number: "))
num2 = int(input("Enter second number: "))
print("LCM:", compute_lcm(num1, num2))
print("GCD:", compute_gcd(num1, num2))
9. Find the Factorial of a Number:
def factorial(n):
if n == 0:
return 1
else:
return n * factorial(n - 1)
num = int(input("Enter a number: "))
print("Factorial:", factorial(num))
10. Implement Quick Sort:
def quick_sort(arr):
if len(arr) <= 1:
return arr
pivot = arr[len(arr) // 2]
left = [x for x in arr if x < pivot]
middle = [x for x in arr if x == pivot]
right = [x for x in arr if x > pivot]
return quick_sort(left) + middle + quick_sort(right)
arr = [12, 11, 13, 5, 6, 7]
sorted_arr = quick_sort(arr)
print("Sorted array:", sorted_arr)
0 Comments