def selectionSort(arr):
for i in range(len(arr)):
min_idx = i
for j in range(i+1, len(arr)):
if arr[min_idx] > arr[j]:
min_idx = j
arr[i], arr[min_idx] = arr[min_idx], arr[i]
This algorithm is also not efficient, but it performs better than Bubble Sort in
some cases.
Quote: "Selection Sort is like selecting the best student to be the class
representative, it's done repeatedly until all positions are filled."
Insertion Sort
Insertion Sort algorithm sorts an array by building a sorted array one item at a
time.
Here's an example of how Insertion Sort works in Python:
def insertionSort(arr):
for i in range(1, len(arr)):
key = arr[i]
j = i-1
while j >=0 and key < arr[j] :
arr[j+1] = arr[j]
j -= 1
arr[j+1] = key
This algorithm performs better than Bubble Sort and Selection Sort, but it's not
efficient for large datasets.
Quote: "Insertion Sort is like arranging a deck of cards, it's simple and efficient
when you have a small number of items to sort."
Merge Sort
Merge Sort algorithm sorts an array by dividing it into half, then sorting each
half, and finally merging the sorted halves.
Here's an example of how Merge Sort works in Python:
def mergeSort(arr):
if len(arr) >1:
mid = len(arr)//2
L = arr[:mid]
R = arr[mid:]
mergeSort(L)
mergeSort(R)
i = j = k = 0
while i < len(L) and j < len(R):
if L[i] < R[j]:
for i in range(len(arr)):
min_idx = i
for j in range(i+1, len(arr)):
if arr[min_idx] > arr[j]:
min_idx = j
arr[i], arr[min_idx] = arr[min_idx], arr[i]
This algorithm is also not efficient, but it performs better than Bubble Sort in
some cases.
Quote: "Selection Sort is like selecting the best student to be the class
representative, it's done repeatedly until all positions are filled."
Insertion Sort
Insertion Sort algorithm sorts an array by building a sorted array one item at a
time.
Here's an example of how Insertion Sort works in Python:
def insertionSort(arr):
for i in range(1, len(arr)):
key = arr[i]
j = i-1
while j >=0 and key < arr[j] :
arr[j+1] = arr[j]
j -= 1
arr[j+1] = key
This algorithm performs better than Bubble Sort and Selection Sort, but it's not
efficient for large datasets.
Quote: "Insertion Sort is like arranging a deck of cards, it's simple and efficient
when you have a small number of items to sort."
Merge Sort
Merge Sort algorithm sorts an array by dividing it into half, then sorting each
half, and finally merging the sorted halves.
Here's an example of how Merge Sort works in Python:
def mergeSort(arr):
if len(arr) >1:
mid = len(arr)//2
L = arr[:mid]
R = arr[mid:]
mergeSort(L)
mergeSort(R)
i = j = k = 0
while i < len(L) and j < len(R):
if L[i] < R[j]: