-
Notifications
You must be signed in to change notification settings - Fork 44
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #379 from ruchikakengal/solutions-adding-
Add Sorting problems
- Loading branch information
Showing
4 changed files
with
48 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,7 @@ | ||
def bubble_sort(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 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,9 @@ | ||
def insertion_sort(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 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,23 @@ | ||
def merge_sort(arr): | ||
if len(arr) <= 1: | ||
return arr | ||
|
||
mid = len(arr) // 2 | ||
left = merge_sort(arr[:mid]) | ||
right = merge_sort(arr[mid:]) | ||
|
||
return merge(left, right) | ||
|
||
def merge(left, right): | ||
result = [] | ||
i = j = 0 | ||
while i < len(left) and j < len(right): | ||
if left[i] < right[j]: | ||
result.append(left[i]) | ||
i += 1 | ||
else: | ||
result.append(right[j]) | ||
j += 1 | ||
result.extend(left[i:]) | ||
result.extend(right[j:]) | ||
return result |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,9 @@ | ||
def selection_sort(arr): | ||
n = len(arr) | ||
for i in range(n): | ||
min_idx = i | ||
for j in range(i+1, n): | ||
if arr[j] < arr[min_idx]: | ||
min_idx = j | ||
arr[i], arr[min_idx] = arr[min_idx], arr[i] | ||
return arr |