Skip to content

Commit b78a55c

Browse files
authored
Merge pull request codeharborhub#1702 from dhairyagothi/main
added sorting algorithms in dsa
2 parents 6416701 + d4b7663 commit b78a55c

File tree

6 files changed

+208
-0
lines changed

6 files changed

+208
-0
lines changed

docs/dsa/algorithms/image-1.png

104 KB
Loading

docs/dsa/algorithms/image-2.png

60.4 KB
Loading
+208
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,208 @@
1+
---
2+
id: sorting-in-dsa
3+
title: Sorting in Data Structures and Algorithms
4+
sidebar_label: Sorting Algorithm
5+
sidebar_position: 1
6+
description: ""
7+
tags:
8+
[dsa,data-algorithms , sorting
9+
]
10+
---
11+
12+
13+
14+
Sorting is a fundamental operation in computer science that arranges a collection of elements in a specific order. There are various sorting algorithms available, each with its own advantages and disadvantages. In this section, we will explore some commonly used sorting algorithms and provide Python code examples for their implementation.
15+
16+
![alt text](image-2.png)
17+
18+
### 1. Bubble Sort
19+
20+
Bubble Sort is a simple comparison-based sorting algorithm. It repeatedly compares adjacent elements and swaps them if they are in the wrong order. This process is repeated until the entire list is sorted.
21+
22+
```python
23+
def bubble_sort(arr):
24+
n = len(arr)
25+
for i in range(n):
26+
for j in range(0, n-i-1):
27+
if arr[j] > arr[j+1]:
28+
arr[j], arr[j+1] = arr[j+1], arr[j]
29+
```
30+
31+
### 2. Selection Sort
32+
33+
Selection Sort is another simple comparison-based sorting algorithm. It divides the input list into two parts: the sorted part at the left end and the unsorted part at the right end. It repeatedly selects the smallest element from the unsorted part and swaps it with the leftmost element of the unsorted part.
34+
35+
```python
36+
def selection_sort(arr):
37+
n = len(arr)
38+
for i in range(n):
39+
min_idx = i
40+
for j in range(i+1, n):
41+
if arr[j] < arr[min_idx]:
42+
min_idx = j
43+
arr[i], arr[min_idx] = arr[min_idx], arr[i]
44+
```
45+
46+
### 3. Insertion Sort
47+
48+
Insertion Sort is an efficient comparison-based sorting algorithm that builds the final sorted array one element at a time. It iterates through the input list and for each element, it finds its correct position in the sorted part of the list and shifts the larger elements to the right.
49+
50+
```python
51+
def insertion_sort(arr):
52+
n = len(arr)
53+
for i in range(1, n):
54+
key = arr[i]
55+
j = i - 1
56+
while j >= 0 and arr[j] > key:
57+
arr[j+1] = arr[j]
58+
j -= 1
59+
arr[j+1] = key
60+
```
61+
62+
### 4. Merge Sort
63+
64+
Merge Sort is a divide-and-conquer sorting algorithm that divides the input list into smaller sublists, sorts them, and then merges them to obtain a sorted list. It recursively divides the list until each sublist contains only one element, and then merges the sublists in a sorted manner.
65+
66+
```python
67+
def merge_sort(arr):
68+
if len(arr) <= 1:
69+
return arr
70+
71+
mid = len(arr) // 2
72+
left = arr[:mid]
73+
right = arr[mid:]
74+
75+
left = merge_sort(left)
76+
right = merge_sort(right)
77+
78+
return merge(left, right)
79+
80+
def merge(left, right):
81+
result = []
82+
i = j = 0
83+
84+
while i < len(left) and j < len(right):
85+
if left[i] < right[j]:
86+
result.append(left[i])
87+
i += 1
88+
else:
89+
result.append(right[j])
90+
j += 1
91+
92+
while i < len(left):
93+
result.append(left[i])
94+
i += 1
95+
96+
while j < len(right):
97+
result.append(right[j])
98+
j += 1
99+
100+
return result
101+
```
102+
103+
### 5. Quick Sort
104+
105+
Quick Sort is a divide-and-conquer sorting algorithm that selects a pivot element and partitions the input list into two sublists, one with elements smaller than the pivot and one with elements greater than the pivot. It then recursively sorts the sublists.
106+
107+
```python
108+
def quick_sort(arr):
109+
if len(arr) <= 1:
110+
return arr
111+
112+
pivot = arr[len(arr) // 2]
113+
left = [x for x in arr if x < pivot]
114+
middle = [x for x in arr if x == pivot]
115+
right = [x for x in arr if x > pivot]
116+
117+
return quick_sort(left) + middle + quick_sort(right)
118+
```
119+
120+
### 6. Heap Sort
121+
122+
Heap Sort is a comparison-based sorting algorithm that uses a binary heap data structure. It first builds a max heap from the input list, then repeatedly extracts the maximum element from the heap and places it at the end of the sorted list.
123+
124+
```python
125+
def heap_sort(arr):
126+
n = len(arr)
127+
128+
for i in range(n // 2 - 1, -1, -1):
129+
heapify(arr, n, i)
130+
131+
for i in range(n - 1, 0, -1):
132+
arr[i], arr[0] = arr[0], arr[i]
133+
heapify(arr, i, 0)
134+
135+
def heapify(arr, n, i):
136+
largest = i
137+
left = 2 * i + 1
138+
right = 2 * i + 2
139+
140+
if left < n and arr[left] > arr[largest]:
141+
largest = left
142+
143+
if right < n and arr[right] > arr[largest]:
144+
largest = right
145+
146+
if largest != i:
147+
arr[i], arr[largest] = arr[largest], arr[i]
148+
heapify(arr, n, largest)
149+
```
150+
151+
152+
### 7. Radix Sort
153+
154+
Radix Sort is a non-comparative sorting algorithm that sorts integers by grouping them by individual digits. It starts by sorting the numbers based on the least significant digit and progressively moves towards the most significant digit. This process is repeated until the numbers are sorted based on all digits.
155+
156+
```python
157+
def radix_sort(arr):
158+
# Find the maximum number to determine the number of digits
159+
max_num = max(arr)
160+
161+
# Perform counting sort for every digit
162+
exp = 1
163+
while max_num // exp > 0:
164+
counting_sort(arr, exp)
165+
exp *= 10
166+
167+
def counting_sort(arr, exp):
168+
n = len(arr)
169+
output = [0] * n
170+
count = [0] * 10
171+
172+
# Count the occurrences of each digit
173+
for i in range(n):
174+
index = arr[i] // exp
175+
count[index % 10] += 1
176+
177+
# Calculate the cumulative count
178+
for i in range(1, 10):
179+
count[i] += count[i - 1]
180+
181+
# Build the output array
182+
i = n - 1
183+
while i >= 0:
184+
index = arr[i] // exp
185+
output[count[index % 10] - 1] = arr[i]
186+
count[index % 10] -= 1
187+
i -= 1
188+
189+
# Copy the sorted elements back to the original array
190+
for i in range(n):
191+
arr[i] = output[i]
192+
```
193+
194+
Radix Sort has a time complexity of O(d * (n + k)), where d is the number of digits, n is the number of elements, and k is the range of values. It is often used for sorting integers with a fixed number of digits.
195+
196+
![alt text](image-1.png)
197+
198+
### Conclusion
199+
200+
In this article, we explored various sorting algorithms commonly used in data structures and algorithms. We provided Python code examples for each algorithm, including Bubble Sort, Selection Sort, Insertion Sort, Merge Sort, Quick Sort, Heap Sort, and Radix Sort.
201+
202+
Each sorting algorithm has its own advantages and disadvantages, and the choice of algorithm depends on the specific requirements of the problem at hand. It's important to consider factors such as time complexity, space complexity, stability, and adaptability when selecting a sorting algorithm.
203+
204+
By understanding these sorting algorithms and their implementations, you can effectively organize and arrange collections of elements in a specific order, which is a fundamental operation in computer science.
205+
206+
Remember to analyze the problem, consider the constraints, and choose the most appropriate sorting algorithm for your specific use case.
207+
208+
Happy sorting!

0 commit comments

Comments
 (0)