Dsa 04
Dsa 04
Introduction to Algorithms
Algorithms are step-by-step procedures for performing tasks or solving problems. Sorting and
searching algorithms are fundamental for organizing and retrieving data efficiently.
Sorting Algorithms
Sorting is the process of arranging data in a specific order (ascending or descending).
Bubble Sort
Python Implementation:
def bubble_sort(arr):
n = len(arr)
for i in range(n):
Selects the smallest element and swaps it with the current index.
Python Implementation:
def selection_sort(arr):
for i in range(len(arr)):
min_idx = i
min_idx = j
Merge Sort
Divide and conquer algorithm that splits the array and merges sorted halves.
Python Implementation:
def merge_sort(arr):
if len(arr) > 1:
mid = len(arr) // 2
L = arr[:mid]
R = arr[mid:]
merge_sort(L)
merge_sort(R)
i=j=k=0
arr[k] = L[i]
i += 1
else:
arr[k] = R[j]
j += 1
k += 1
Quick Sort
Python Implementation:
def quick_sort(arr):
if len(arr) <= 1:
return arr
pivot = arr[len(arr) // 2]
Searching Algorithms
Efficient searching techniques to find elements within a collection.
Linear Search
Python Implementation:
for i in range(len(arr)):
if arr[i] == x:
return i
return -1
Binary Search
Efficiently finds an element in a sorted list by dividing the search interval in half.
Python Implementation:
if arr[mid] == x:
return mid
low = mid + 1
else:
high = mid - 1
return -1
Comparison of Algorithms
Conclusion
Sorting and searching algorithms play a vital role in efficient data handling. The next part will
focus on advanced algorithms like dynamic programming and greedy methods.