Download as pdf or txt
Download as pdf or txt
You are on page 1of 4

DEPARTMENT OF

COMPUTER SCIENCE & ENGINEERING

Experiment –3.1

Student Name: Ashwani Kumar UID:21BCS4688


Branch: BE- CSE Section/Group:713/A
Semester: 4th Date of Performance:4thMay 23
Subject Name: Programming with Python Subject Code:21CSP-259

Aim of the practical: Program to demonstrate the basis learning of searching & sorting.

Objective: To learn how to search & sort in problem

Program Code-

1. Python program to implement linear search.

Code:-

def linear_search(arr, x):

n = len(arr)
for i in range(n):
if arr[i] == x:
return i
return -1

arr = [5, 2, 4, 8, 9, 1, 7]
x=8
index = linear_search(arr, x)
if index == -1:
print(f"{x} not found in array.")
else:
print(f"{x} found at index {index}.")

Output:
DEPARTMENT OF
COMPUTER SCIENCE & ENGINEERING

2. Python program to implement bubble sort.

Code-

def bubble_sort(arr):

n = len(arr)
for i in range(n):
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 is:", arr)

Output:

3. Python program to implement binary search without recursion.

Code-
def binary_search(arr, x):

left = 0
right = len(arr) - 1

while left <= right:


mid = (left + right) // 2

if arr[mid] == x:
DEPARTMENT OF
COMPUTER SCIENCE & ENGINEERING

return mid

elif arr[mid] < x:


left = mid + 1

else:
right = mid - 1

return -1

arr = [2, 3, 4, 10, 40]


x = 10
index = binary_search(arr, x)
if index == -1:
print(f"{x} not found in array.")
else:
print(f"{x} found at index {index}.")

Output:

4. Python program to implement selection sort.

Code-

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
DEPARTMENT OF
COMPUTER SCIENCE & ENGINEERING

arr[i], arr[min_idx] = arr[min_idx], arr[i]

arr = [64, 25, 12, 22, 11]


selection_sort(arr)
print("Sorted array is:", arr)

Output:

You might also like