Sorting_Algorithm
Sorting_Algorithm
Insertion Sort
Algorithm Steps:
3. Shift all elements that are greater than the current element to the right.
4. Insert the current element into the correct position in the sorted subarray.
🔹 2. Selection Sort
Algorithm Steps:
3. Swap the minimum element with the first element of the unsorted part.
for i in range(len(arr)):
min_idx = i
for j in range(i + 1, len(arr)):
if arr[j] < arr[min_idx]:
min_idx = j
arr[i], arr[min_idx] = arr[min_idx], arr[i]
🔹 3. Bubble Sort
Algorithm Steps:
5. After each pass, the largest unsorted element will have “bubbled” to its correct
position.
Pseudocode:
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]
🔹 4. Merge Sort
Algorithm Steps:
Pseudocode:
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
while i < len(L) and j < len(R):
if L[i] < R[j]:
arr[k] = L[i]
i += 1
else:
arr[k] = R[j]
j += 1
k += 1
🔹 5. Quick Sort
Algorithm Steps:
Pseudocode:
def quick_sort(arr):
if len(arr) <= 1:
return arr
pivot = arr[-1]
left = [x for x in arr[:-1] if x <= pivot]
right = [x for x in arr[:-1] if x > pivot]
return quick_sort(left) + [pivot] + quick_sort(right)
🔹 6. Counting Sort
Algorithm Steps:
3. Count the frequency of each element and store it in the count array.
4. Modify the count array by adding previous counts to get cumulative counts.
5. Use the count array to place elements in the correct position in the output
array.
6. Copy the sorted output array back into the original array.
Pseudocode:
def counting_sort(arr):
max_val = max(arr)
min_val = min(arr)
range_of_elements = max_val - min_val + 1
count = [0] * range_of_elements
output = [0] * len(arr)
for i in range(len(arr)):
arr[i] = output[i]
🔹 7. Radix Sort
Algorithm Steps:
Pseudocode:
for i in range(n):
index = (arr[i] // exp) % 10
count[index] += 1
for i in reversed(range(n)):
index = (arr[i] // exp) % 10
output[count[index] - 1] = arr[i]
count[index] -= 1
for i in range(n):
arr[i] = output[i]
def radix_sort(arr):
max_num = max(arr)
exp = 1
while max_num // exp > 0:
counting_sort_digit(arr, exp)
exp *= 10
🔹 8. Heap Sort
Algorithm Steps:
Pseudocode:
def heap_sort(arr):
n = len(arr)
for i in range(n // 2 - 1, -1, -1):
heapify(arr, n, i)
for i in range(n - 1, 0, -1):
arr[i], arr[0] = arr[0], arr[i]
heapify(arr, i, 0)
🔹 9. Bucket Sort
Algorithm Steps:
Pseudocode:
def bucket_sort(arr):
n = len(arr)
buckets = [[] for _ in range(n)]
k=0
for bucket in buckets:
for num in bucket:
arr[k] = num
k += 1