Program 4: Binary Search Tree

Next Program
# Node structure for the BST create_node <- function(value) { return(list(value = value, left = NULL, right = NULL)) } # Insert function for BST insert_bst <- function(root, value) { if (is.null(root)) { return(create_node(value)) # Insert as new node if root is NULL } if (value < root$value) { root$left <- insert_bst(root$left, value) # Insert in left subtree } else { root$right <- insert_bst(root$right, value) # Insert in right subtree } return(root) } # Inorder traversal function (to print BST in sorted order) inorder_traversal <- function(root) { if (!is.null(root)) { inorder_traversal(root$left) # Traverse left subtree print(root$value) # Print node's value inorder_traversal(root$right) # Traverse right subtree } } # Example usage: bst_root <- NULL values <- c(50, 30, 20, 40, 70, 60, 80) # Insert values into BST for (val in values) { bst_root <- insert_bst(bst_root, val) } # Print the BST in sorted order using inorder traversal inorder_traversal(bst_root)
# Define the quicksort function quicksort <- function(arr) { # Base case: if the array has 0 or 1 elements, it's already sorted if (length(arr) <= 1) { return(arr) } # Choose a pivot (e.g., the first element) pivot <- arr[1] # Partition the array into elements less than, equal to, and greater than the pivot less <- arr[arr < pivot] equal <- arr[arr == pivot] greater <- arr[arr > pivot] # Recursively apply quicksort to the partitions and combine the results return(c(quicksort(less), equal, quicksort(greater))) } # Example usage input_array <- c(3, 6, 8, 10, 1, 2, 1) sorted_array <- quicksort(input_array) print(sorted_array)