0% found this document useful (0 votes)
8 views5 pages

Daa

The document contains implementations of three algorithms: Graham Scan, Randomized Quick Sort, and Jarvis March for computing convex hulls and sorting arrays. Each algorithm includes code snippets, user input handling, and optional visualization using matplotlib. The document emphasizes the requirement of at least three points for convex hull calculations.

Uploaded by

jayavardhand2004
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)
8 views5 pages

Daa

The document contains implementations of three algorithms: Graham Scan, Randomized Quick Sort, and Jarvis March for computing convex hulls and sorting arrays. Each algorithm includes code snippets, user input handling, and optional visualization using matplotlib. The document emphasizes the requirement of at least three points for convex hull calculations.

Uploaded by

jayavardhand2004
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/ 5

Digital Assignment

22BCE0754
Jaya vardhan

Graham Scan

Code:

import matplotlib.pyplot as plt

# Function to find the orientation of three points


def orientation(p, q, r):
# Cross product to determine orientation
val = (q[1] - p[1]) * (r[0] - q[0]) - (q[0] - p[0]) * (r[1] - q[1])
if val == 0:
return 0 # Collinear
return 1 if val > 0 else -1 # Clockwise or Counterclockwise

# Function to compute the convex hull using Graham Scan


def graham_scan(points):
# Sort points by x-coordinate, and by y if x-coordinates are the same
points = sorted(points, key=lambda point: (point[0], point[1]))
# Initialize two parts of the hull
lower_hull = []
upper_hull = []

# Build the lower hull


for p in points:
while len(lower_hull) >= 2 and orientation(lower_hull[-2], lower_hull[-1], p) != -1:
lower_hull.pop()
lower_hull.append(p)

# Build the upper hull


for p in reversed(points):
while len(upper_hull) >= 2 and orientation(upper_hull[-2], upper_hull[-1], p) != -1:
upper_hull.pop()
upper_hull.append(p)

# Combine lower and upper hull to get the convex hull


return lower_hull[:-1] + upper_hull[:-1] # Remove last point to avoid duplication

# Get user input for points


print("Enter points as x, y pairs (e.g., 1,2). Enter 'done' to finish:")
points = []
while True:
inp = input("Point: ")
if inp.lower() == 'done':
break
try:
x, y = map(float, inp.split(','))
points.append((x, y))
except ValueError:
print("Invalid input. Please enter as x,y.")
# Compute the convex hull
if len(points) < 3:
print("At least 3 points are required to form a convex hull.")
else:
convex_hull = graham_scan(points)
print("Convex Hull:", convex_hull)

# Optional: Visualize the points and the convex hull


x, y = zip(*points)
plt.scatter(x, y, label='Points')
hull_x, hull_y = zip(*(convex_hull + [convex_hull[0]])) # Loop back to the first point
plt.plot(hull_x, hull_y, 'r-', label='Convex Hull')
plt.legend()
plt.show()

Output:

Randomized Quick sort

Code:
import random

# Function for partitioning the array


def partition(arr, low, high):
pivot = arr[high] # Pivot element
i = low - 1 # Pointer for the smaller element

for j in range(low, high):


if arr[j] < pivot:
i += 1
arr[i], arr[j] = arr[j], arr[i]

# Place the pivot element at its correct position


arr[i + 1], arr[high] = arr[high], arr[i + 1]
return i + 1

# Function to choose a random pivot and partition the array


def randomized_partition(arr, low, high):
pivot_index = random.randint(low, high) # Choose a random pivot
arr[pivot_index], arr[high] = arr[high], arr[pivot_index] # Swap pivot with the last element
return partition(arr, low, high)

# Function to perform randomized quick sort


def randomized_quick_sort(arr, low, high):
if low < high:
# Partition the array around the randomly chosen pivot
pi = randomized_partition(arr, low, high)

# Recursively sort the two partitions


randomized_quick_sort(arr, low, pi - 1)
randomized_quick_sort(arr, pi + 1, high)

# User input
arr = list(map(int, input("Enter the elements of the array (separated by spaces): ").split()))

print("Original array:", arr)


randomized_quick_sort(arr, 0, len(arr) - 1)
print("Sorted array:", arr)

Output:
Jarvis March

Code:
import matplotlib.pyplot as plt

# Function to find the point with the lowest x-coordinate (ties broken by y-coordinate)
def leftmost_point(points):
return min(points, key=lambda p: (p[0], p[1]))

# Function to calculate orientation


def orientation(p, q, r):
# Compute cross product to determine orientation
val = (q[1] - p[1]) * (r[0] - q[0]) - (q[0] - p[0]) * (r[1] - q[1])
return val

# Jarvis March algorithm (Gift Wrapping)


def jarvis_march(points):
# Ensure there are enough points to form a convex hull
if len(points) < 3:
return "At least 3 points are required to form a convex hull."

hull = [] # Store the points forming the convex hull


start = leftmost_point(points) # Start from the leftmost point
hull.append(start)
current = start

while True:
next_point = points[0] # Pick an arbitrary point initially
for point in points:
if point == current:
continue
# Update next_point if it is more counterclockwise
if next_point == current or orientation(current, next_point, point) < 0:
next_point = point
current = next_point
if current == start: # If we’ve wrapped back to the starting point
break
hull.append(current)

return hull

# User input
print("Enter points as x, y pairs (e.g., 1,2). Enter 'done' to finish:")
points = []
while True:
inp = input("Point: ")
if inp.lower() == 'done':
break
try:
x, y = map(float, inp.split(','))
points.append((x, y))
except ValueError:
print("Invalid input. Please enter as x,y.")

# Compute the convex hull


convex_hull = jarvis_march(points)
if isinstance(convex_hull, str): # Handle case of insufficient points
print(convex_hull)
else:
print("Convex Hull:", convex_hull)

# Optional: Visualize the points and convex hull


x, y = zip(*points)
plt.scatter(x, y, label='Points')
hull_x, hull_y = zip(*(convex_hull + [convex_hull[0]])) # Loop back to the start point
plt.plot(hull_x, hull_y, 'r-', label='Convex Hull')
plt.legend()
plt.show()

Output:

You might also like