Different Sorting Algorithms Explained
Sorting is one of the most important concepts in programming. It helps in arranging data in a specific order, usually ascending or descending. In this blog, we will look at some common sorting algorithms taught in the session.
What is Sorting
Sorting means arranging elements of an array in a particular order. For example
Input
[5, 2, 9, 1]
Output
[1, 2, 5, 9]
1 Bubble Sort
Bubble sort repeatedly compares adjacent elements and swaps them if they are in the wrong order.
Steps
1 Compare adjacent elements
2 Swap if needed
3 Repeat until array is sorted
Code
```python id="bs1"
def bubbleSort(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]
return arr
---
## 2 Selection Sort
Selection sort finds the smallest element and places it at the correct position.
### Steps
1 Find minimum element
2 Swap with first element
3 Repeat for remaining array
### Code
```python id="ss1"
def selectionSort(arr):
n = len(arr)
for i in range(n):
min_index = i
for j in range(i + 1, n):
if arr[j] < arr[min_index]:
min_index = j
arr[i], arr[min_index] = arr[min_index], arr[i]
return arr
3 Insertion Sort
Insertion sort builds the sorted array one element at a time.
Steps
1 Take one element
2 Place it in correct position in sorted part
3 Repeat for all elements
Code
```python id="is1"
def insertionSort(arr):
for i in range(1, len(arr)):
key = arr[i]
j = i - 1
while j >= 0 and arr[j] > key:
arr[j + 1] = arr[j]
j -= 1
arr[j + 1] = key
return arr
---
## 4 Merge Sort
Merge sort divides the array into halves, sorts them, and merges them.
### Code
```python id="ms1"
def mergeSort(arr):
if len(arr) > 1:
mid = len(arr) // 2
left = arr[:mid]
right = arr[mid:]
mergeSort(left)
mergeSort(right)
i = j = k = 0
while i < len(left) and j < len(right):
if left[i] < right[j]:
arr[k] = left[i]
i += 1
else:
arr[k] = right[j]
j += 1
k += 1
while i < len(left):
arr[k] = left[i]
i += 1
k += 1
while j < len(right):
arr[k] = right[j]
j += 1
k += 1
return arr
5 Quick Sort
Quick sort selects a pivot and partitions the array around it.
Code
```python id="qs1"
def quickSort(arr):
if len(arr) <= 1:
return arr
pivot = arr[0]
left = [x for x in arr[1:] if x <= pivot]
right = [x for x in arr[1:] if x > pivot]
return quickSort(left) + [pivot] + quickSort(right)
---
## 6 Counting Sort
Counting sort is used when the range of numbers is small.
### Code
```python id="cs1"
def countingSort(arr):
max_val = max(arr)
count = [0] * (max_val + 1)
for num in arr:
count[num] += 1
result = []
for i in range(len(count)):
result.extend([i] * count[i])
return result
Conclusion
Sorting algorithms are essential for efficient data processing. Each algorithm works differently and is suitable for different scenarios.
Practice these algorithms to understand how data can be arranged efficiently.
Top comments (0)