# Quick Sort function
quick_sort <- function(arr) {
if (length(arr) <= 1) {
return(arr)
}
pivot <- arr[1]
less <- arr[arr < pivot]
equal <- arr[arr == pivot]
greater <- arr[arr > pivot]
return(c(quick_sort(less), equal, quick_sort(greater)))
}
# Binary Search function (assumes the array is sorted)
binary_search <- function(arr, target) {
left <- 1
right <- length(arr)
while (left <= right) {
mid <- floor((left + right) / 2)
if (arr[mid] == target) {
return(mid) # Found the target element
} else if (arr[mid] < target) {
left <- mid + 1
} else {
right <- mid - 1
}
}
return(-1) # Target element not found
}
# Example data
data <- c(5, 8, 1, 6, 3, 7, 2, 4)
target <- 6
# Sort the data using Quick Sort
sorted_data <- quick_sort(data)
# Perform Binary Search to find the target
result <- binary_search(sorted_data, target)
# Print the result
if (result != -1) {
cat("Element", target, "found at index", result, "\n")
} else {
cat("Element", target, "not found in the sorted array.\n")
}
0 Comments