Skip to content

Commit 0c62105

Browse files
Merge pull request raviprakashdev#6 from swapniljha001/master
Added `Merge Sort.py` and related documentation.
2 parents 9da12a0 + f5dba06 commit 0c62105

3 files changed

Lines changed: 79 additions & 4 deletions

File tree

File renamed without changes.

Merge Sort.py

Lines changed: 71 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,71 @@
1+
# Merge Sort implementation
2+
# Average Time Complexity is O(nlog(n))
3+
4+
# Merges two subarrays of arr[]
5+
# First subarray is arr[l..n]
6+
# Second subarray is arr[n+1..r]
7+
8+
def merge(arr, l, n, r):
9+
n1 = n - l + 1
10+
n2 = r - n
11+
12+
# create temp arrays
13+
L = [0] * (n1)
14+
R = [0] * (n2)
15+
16+
# Copy data to temp arrays
17+
for i in range(0 , n1):
18+
L[i] = arr[l + i]
19+
20+
for j in range(0 , n2):
21+
R[j] = arr[n + 1 + j]
22+
23+
# Merge the temp back into arr[l..r]
24+
i = 0
25+
j = 0
26+
k = l
27+
28+
while i < n1 and j < n2 :
29+
if L[i] <= R[j]:
30+
arr[k] = L[i]
31+
i += 1
32+
else:
33+
arr[k] = R[j]
34+
j += 1
35+
k += 1
36+
37+
while i < n1:
38+
arr[k] = L[i]
39+
i += 1
40+
k += 1
41+
42+
# Copy the remaining elements of R[]
43+
while j < n2:
44+
arr[k] = R[j]
45+
j += 1
46+
k += 1
47+
48+
def mergeSort(arr,l,r):
49+
if l < r:
50+
51+
# Same as (l+r)//2, but avoids overflow for
52+
# large l and n
53+
n = (l+(r-1))//2
54+
55+
# Sort first and second halves
56+
mergeSort(arr, l, n)
57+
mergeSort(arr, n+1, r)
58+
merge(arr, l, n, r)
59+
60+
# Receiving an input from the user
61+
arr = []
62+
n = int(input("Enter number of elements : "))
63+
for i in range(0, n):
64+
ele = int(input())
65+
arr.append(ele)
66+
67+
# Calling mergeSort function
68+
mergeSort(arr,0,n-1)
69+
print ("\n\nSorted array is")
70+
for i in range(n):
71+
print ("%d" %arr[i])

README.md

Lines changed: 8 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,14 @@
11
# simplePythonProgram
22

3-
This file contains 2 programs
4-
- helloworld.py: a simple hello world program
5-
- spam.py: a simple program to give spam message to anyone
3+
This repo contains the following files:
4+
- `Bubble Sort_2.py`: a bubble sort program
5+
- `BubbleSort.py`: another bubble sort program
6+
- `Merge Sort.py`: a merge sort implementation program with user-received input.
7+
- `README.md`: this file
8+
- `helloworld.py`: a simple hello world program
9+
- `spam.py`: a simple program to give spam message to anyone
610

711
To run spam.py install pyautogui
812
<pre>
913
<code>pip install pyautogui</code>
10-
</pre>
14+
</pre>

0 commit comments

Comments
 (0)