0% found this document useful (0 votes)
12 views19 pages

41-52

The document covers various algorithms and data structures including hash key determination, linear sequential search, sorting methods, and binary trees. It provides implementations for insertion sort, bubble sort, heap sort, and binary search, along with examples and explanations of their efficiency. Additionally, it discusses creating vectors from positive elements in an array and introduces the concept of singly linked lists.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views19 pages

41-52

The document covers various algorithms and data structures including hash key determination, linear sequential search, sorting methods, and binary trees. It provides implementations for insertion sort, bubble sort, heap sort, and binary search, along with examples and explanations of their efficiency. Additionally, it discusses creating vectors from positive elements in an array and introduces the concept of singly linked lists.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 19

40. The essence of the method for determining hash keys.

41. Explain the linear sequential search algorithm


with an example.
42. Print the largest element of the list.
43. Classification of sorting, sorting methods and
their efficiency.
44. Algorithm and program for creating a binary
tree.

# Define the Node class for binary tree nodes


class Node:
def __init__(self, data):
self.data = data # The value of the node
self.left = None # Left child node
self.right = None # Right child node

# Define the BinaryTree class


class BinaryTree:
def __init__(self):
self.root = None # Initially, the tree is empty

def insert(self, data):


if self.root is None:
self.root = Node(data) # Create the root node if the tree is empty
else:
self._insert_recursive(self.root, data)

def _insert_recursive(self, node, data):


# Recursively insert data into the left or right subtree
if data < node.data:
if node.left is None:
node.left = Node(data) # Insert new node as left child
else:
self._insert_recursive(node.left, data) # Recurse into left subtree
else:
if node.right is None:
node.right = Node(data) # Insert new node as right child
else:
self._insert_recursive(node.right, data) # Recurse into right subtree
# Pre-order traversal (root -> left -> right)
def pre_order(self, node):
if node:
print(node.data, end=" ") # Visit the node
self.pre_order(node.left) # Recurse on the left subtree
self.pre_order(node.right) # Recurse on the right subtree

# In-order traversal (left -> root -> right)


def in_order(self, node):
if node:
self.in_order(node.left) # Recurse on the left subtree
print(node.data, end=" ") # Visit the node
self.in_order(node.right) # Recurse on the right subtree

# Post-order traversal (left -> right -> root)


def post_order(self, node):
if node:
self.post_order(node.left) # Recurse on the left subtree
self.post_order(node.right) # Recurse on the right subtree
print(node.data, end=" ") # Visit the node

# Example usage
if __name__ == "__main__":
tree = BinaryTree()

# Insert elements into the binary tree


tree.insert(50)
tree.insert(30)
tree.insert(70)
tree.insert(20)
tree.insert(40)
tree.insert(60)
tree.insert(80)

print("Pre-order Traversal:")
tree.pre_order(tree.root) # Output: 50 30 20 40 70 60 80

print("\nIn-order Traversal:")
tree.in_order(tree.root) # Output: 20 30 40 50 60 70 80

print("\nPost-order Traversal:")
tree.post_order(tree.root) # Output: 20 40 30 60 80 70 50

45. Sort the elements of an array by insertion sort


and print it.
# Function to perform insertion sort
def insertion_sort(arr):
# Traverse through the array starting from the second element
for i in range(1, len(arr)):
key = arr[i] # The current element to be inserted
j = i - 1 # Start comparing with the previous element

# Shift elements of arr[0..i-1] that are greater than key to one position ahead
while j >= 0 and arr[j] > key:
arr[j + 1] = arr[j]
j -= 1

# Insert the current element into its correct position


arr[j + 1] = key

# Example array to sort


arr = [12, 11, 13, 5, 6]

# Print original array


print("Original Array:")
print(arr)

# Perform insertion sort


insertion_sort(arr)

# Print sorted array


print("Sorted Array:")
print(arr)

46. Explain bubble sort with an example.


# Function to perform bubble sort
def bubble_sort(arr):
n = len(arr)

# Traverse through all elements of the


array
for i in range(n):
swapped = False

for j in range(0, n - i - 1):

if arr[j] > arr[j + 1]:

arr[j], arr[j + 1] = arr[j + 1],


arr[j]
swapped = True
# If no two elements were swapped
in the inner loop, break
if not swapped:
break

# Example array
arr = [5, 1, 4, 2, 8]

# Print original array


print("Original Array:", arr)
# Perform bubble sort
bubble_sort(arr)
# Print sorted array
print("Sorted Array:", arr)

47. Recursive data structure, recursive triad.


48. Determine the largest element of a list and print
it. ==== > 42

49. Explain the pyramid sort algorithm with an


example.

# Function to heapify a subtree rooted at index i


def heapify(arr, n, i):
largest = i # Initialize largest as root
left = 2 * i + 1 # Left child
right = 2 * i + 2 # Right child

# Check if left child exists and is greater than root


if left < n and arr[left] > arr[largest]:
largest = left

# Check if right child exists and is greater than root


if right < n and arr[right] > arr[largest]:
largest = right
# If the largest is not root, swap and continue heapifying
if largest != i:
arr[i], arr[largest] = arr[largest], arr[i]
heapify(arr, n, largest)

# Heap Sort function


def heap_sort(arr):
n = len(arr)

# Build a max-heap
for i in range(n // 2 - 1, -1, -1):
heapify(arr, n, i)

# Extract elements one by one


for i in range(n - 1, 0, -1):
# Swap current root with the end
arr[i], arr[0] = arr[0], arr[i]
# Heapify the reduced heap
heapify(arr, i, 0)

# Example array
arr = [4, 10, 3, 5, 1]

# Perform heap sort


heap_sort(arr)

# Print the sorted array


print("Sorted array:", arr)
50. Write a binary search condition and algorithm,
program.

def binary_search(arr, x):


low = 0
high = len(arr) - 1

while low <= high:


mid = (low + high) // 2

# Check if x is present at mid


if arr[mid] == x:
return mid
# If x is greater, ignore the left half
elif arr[mid] < x:
low = mid + 1
# If x is smaller, ignore the right half
else:
high = mid - 1

# Element not found


return -1

# Example usage
arr = [1, 3, 5, 7, 9, 11]
target = 7

# Perform binary search


result = binary_search(arr, target)

if result != -1:
print(f"Element found at index {result}")
else:
print("Element not found")

Recursive Implementation in Python

python
Copy code

def binary_search_recursive(arr, low, high, x):


# Base case: If the range is invalid
if low > high:
return -1

# Calculate mid
mid = (low + high) // 2

# Check if x is present at mid


if arr[mid] == x:
return mid
# If x is greater, search the right half
elif arr[mid] < x:
return binary_search_recursive(arr, mid + 1, high, x)
# If x is smaller, search the left half
else:
return binary_search_recursive(arr, low, mid - 1, x)

# Example usage
arr = [1, 3, 5, 7, 9, 11]
target = 9

# Perform binary search


result = binary_search_recursive(arr, 0, len(arr) - 1, target)

if result != -1:
print(f"Element found at index {result}")
else:
print("Element not found")
51. Create a vector from the positive elements of an
array.

def create_positive_vector(arr):
# Initialize an empty vector
positive_vector = []

# Traverse the array


for num in arr:
# Add only positive elements to the vector
if num > 0:
positive_vector.append(num)

return positive_vector

# Example array
array = [-3, 5, -1, 7, 0, -8, 12]

# Create vector from positive elements


positive_vector = create_positive_vector(array)

# Output the result


print("Original array:", array)
print("Positive vector:", positive_vector)
52. What is a singly linked list structure and what
are the algorithms for operating on it?

You might also like