Skip to content
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Commit ca8aab8

Browse files
committedJul 30, 2016
Merge to update my local repo.
2 parents 473022a + 93443cb commit ca8aab8

File tree

10 files changed

+458
-169
lines changed

10 files changed

+458
-169
lines changed
 

‎BinarySeach.py

Lines changed: 0 additions & 30 deletions
This file was deleted.

‎BubbleSort.py

Lines changed: 39 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -1,26 +1,39 @@
1-
2-
3-
array=[];
4-
5-
# input
6-
print ("Enter any 6 Numbers for Unsorted Array : ");
7-
for i in range(0, 6):
8-
n=input();
9-
array.append(int(n));
10-
11-
# Sorting
12-
print("")
13-
for i in range(0, 6):
14-
for j in range(0,5):
15-
if (array[j]>array[j+1]):
16-
temp=array[j];
17-
array[j]=array[j+1];
18-
array[j+1]=temp;
19-
20-
# Output
21-
for i in range(0,6):
22-
print(array[i]);
23-
24-
25-
26-
1+
import sys
2+
3+
4+
def simple_bubble_sort(int_list):
5+
count = len(int_list)
6+
swapped = True
7+
while (swapped):
8+
swapped = False
9+
for j in range(count - 1):
10+
if (int_list[j] > int_list[j + 1]):
11+
int_list[j], int_list[j + 1] = int_list[j + 1], int_list[j]
12+
swapped = True
13+
return int_list
14+
15+
16+
def main():
17+
# Python 2's `raw_input` has been renamed to `input` in Python 3
18+
if sys.version_info.major < 3:
19+
input_function = raw_input
20+
else:
21+
input_function = input
22+
23+
try:
24+
print("Enter numbers separated by spaces:")
25+
s = input_function()
26+
inputs = list(map(int, s.split(' ')))
27+
if len(inputs) < 2:
28+
print('No Enough values to sort!')
29+
raise Exception
30+
31+
except Exception as e:
32+
print(e)
33+
else:
34+
sorted_input = simple_bubble_sort(inputs)
35+
print('\nSorted list (min to max): {}'.format(sorted_input))
36+
37+
if __name__ == '__main__':
38+
print('==== Bubble Sort ====\n')
39+
main()

‎InsertionSort.py

Lines changed: 33 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -1,25 +1,40 @@
1-
array=[];
1+
import sys
22

3-
# input
4-
print ("Enter any 6 Numbers for Unsorted Array : ");
5-
for i in range(0, 6):
6-
n=input();
7-
array.append(int(n));
83

9-
# Sorting
10-
print("")
11-
for i in range(1, 6):
12-
temp=array[i]
13-
j=i-1;
14-
while(j>=0 and temp<array[j]):
15-
array[j+1]=array[j];
16-
j-=1;
17-
array[j+1]=temp;
4+
def simple_insertion_sort(int_list):
5+
count = len(int_list)
6+
for i in range(1, count):
7+
temp = int_list[i]
8+
j = i - 1
9+
while(j >= 0 and temp < int_list[j]):
10+
int_list[j + 1] = int_list[j]
11+
j -= 1
12+
int_list[j + 1] = temp
1813

19-
# Output
20-
for i in range(0,6):
21-
print(array[i]);
14+
return int_list
2215

2316

17+
def main():
18+
# Python 2's `raw_input` has been renamed to `input` in Python 3
19+
if sys.version_info.major < 3:
20+
input_function = raw_input
21+
else:
22+
input_function = input
2423

24+
try:
25+
print("Enter numbers separated by spaces:")
26+
s = input_function()
27+
inputs = list(map(int, s.split(' ')))
28+
if len(inputs) < 2:
29+
print('No Enough values to sort!')
30+
raise Exception
2531

32+
except Exception as e:
33+
print(e)
34+
else:
35+
sorted_input = simple_insertion_sort(inputs)
36+
print('\nSorted list (min to max): {}'.format(sorted_input))
37+
38+
if __name__ == '__main__':
39+
print('==== Insertion Sort ====\n')
40+
main()

‎LinearSearch.py

Lines changed: 31 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -1,21 +1,32 @@
1-
def sequentialSearch(alist, item):
2-
pos = 0
3-
found = False
4-
5-
while pos < len(alist) and not found:
6-
7-
if alist[pos] == item:
8-
found = True
9-
print("Found")
10-
else:
11-
pos = pos+1
12-
if found == False:
13-
print("Not found")
14-
return found
15-
16-
print("Enter numbers seprated by space")
17-
s = input()
18-
numbers = list(map(int, s.split()))
19-
trgt =int( input('enter a single number to be found in the list '))
20-
sequentialSearch(numbers, trgt)
1+
import sys
212

3+
4+
def sequential_search(alist, target):
5+
for index, item in enumerate(alist):
6+
if item == target:
7+
print("Found target {} at index {}".format(target, index))
8+
break
9+
else:
10+
print("Not found")
11+
12+
13+
def main():
14+
# Python 2's `raw_input` has been renamed to `input` in Python 3
15+
if sys.version_info.major < 3:
16+
input_function = raw_input
17+
else:
18+
input_function = input
19+
20+
try:
21+
print("Enter numbers separated by spaces")
22+
s = input_function()
23+
inputs = list(map(int, s.split(' ')))
24+
target = int(input_function('\nEnter a number to be found in list: '))
25+
except Exception as e:
26+
print(e)
27+
else:
28+
sequential_search(inputs, target)
29+
30+
if __name__ == '__main__':
31+
print('==== Linear Search ====\n')
32+
main()

‎MergeSort.py

Lines changed: 57 additions & 34 deletions
Original file line numberDiff line numberDiff line change
@@ -1,36 +1,59 @@
1-
def mergeSort(alist):
2-
print("Splitting ",alist)
3-
if len(alist)>1:
4-
mid = len(alist)//2
5-
lefthalf = alist[:mid]
6-
righthalf = alist[mid:]
7-
mergeSort(lefthalf)
8-
mergeSort(righthalf)
9-
i=0
10-
j=0
11-
k=0
12-
while i < len(lefthalf) and j < len(righthalf):
13-
if lefthalf[i] < righthalf[j]:
14-
alist[k]=lefthalf[i]
15-
i=i+1
1+
import sys
2+
3+
4+
def merge_sort(alist):
5+
print("Splitting ", alist)
6+
if len(alist) > 1:
7+
mid = len(alist) // 2
8+
left_half = alist[:mid]
9+
right_half = alist[mid:]
10+
merge_sort(left_half)
11+
merge_sort(right_half)
12+
i = j = k = 0
13+
14+
while i < len(left_half) and j < len(right_half):
15+
if left_half[i] < right_half[j]:
16+
alist[k] = left_half[i]
17+
i += 1
1618
else:
17-
alist[k]=righthalf[j]
18-
j=j+1
19-
k=k+1
20-
21-
while i < len(lefthalf):
22-
alist[k]=lefthalf[i]
23-
i=i+1
24-
k=k+1
25-
26-
while j < len(righthalf):
27-
alist[k]=righthalf[j]
28-
j=j+1
29-
k=k+1
30-
print("Merging ",alist)
31-
32-
print("Enter numbers seprated by space")
33-
s = input()
34-
numbers = list(map(int, s.split()))
35-
mergeSort(numbers)
19+
alist[k] = right_half[j]
20+
j += 1
21+
k += 1
22+
23+
while i < len(left_half):
24+
alist[k] = left_half[i]
25+
i += 1
26+
k += 1
27+
28+
while j < len(right_half):
29+
alist[k] = right_half[j]
30+
j += 1
31+
k += 1
32+
print("Merging ", alist)
33+
return alist
34+
35+
36+
def main():
37+
# Python 2's `raw_input` has been renamed to `input` in Python 3
38+
if sys.version_info.major < 3:
39+
input_function = raw_input
40+
else:
41+
input_function = input
42+
43+
try:
44+
print("Enter numbers separated by spaces:")
45+
s = input_function()
46+
inputs = list(map(int, s.split(' ')))
47+
if len(inputs) < 2:
48+
print('No Enough values to sort!')
49+
raise Exception
50+
51+
except Exception as e:
52+
print(e)
53+
else:
54+
sorted_input = merge_sort(inputs)
55+
print('\nSorted list (min to max): {}'.format(sorted_input))
3656

57+
if __name__ == '__main__':
58+
print('==== Merge Sort ====\n')
59+
main()

‎QuickSort.py

Lines changed: 29 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -1,31 +1,41 @@
1+
import sys
12

2-
def quicksort(A, p, r):
3+
4+
def quick_sort(A, p, r):
35
if p < r:
46
q = partition(A, p, r)
5-
quicksort(A, p, q - 1)
6-
quicksort(A, q + 1, r)
7+
quick_sort(A, p, q - 1)
8+
quick_sort(A, q + 1, r)
9+
return A
710

811

912
def partition(A, p, r):
10-
x = A[r]
1113
i = p - 1
1214
for j in range(p, r):
13-
if A[j] <= x:
15+
if A[j] <= A[r]:
1416
i += 1
15-
tmp = A[i]
16-
A[i] = A[j]
17-
A[j] = tmp
18-
tmp = A[i+1]
19-
A[i+1] = A[r]
20-
A[r] = tmp
17+
A[i], A[j] = A[j], A[i]
18+
A[i + 1], A[r] = A[r], A[i + 1]
2119
return i + 1
2220

2321

24-
if __name__ == "__main__":
25-
print('Enter values seperated by space:')
26-
A = [int (item) for item in input().split(' ')]
27-
# A = [23, 45, 43, 12, 67, 98, 123, 99]
28-
# partition(A, 0, 7)
29-
print(A)
30-
quicksort(A, 0, 7)
31-
print(A)
22+
def main():
23+
# Python 2's `raw_input` has been renamed to `input` in Python 3
24+
if sys.version_info.major < 3:
25+
input_function = raw_input
26+
else:
27+
input_function = input
28+
29+
try:
30+
print("Enter numbers separated by spaces")
31+
s = input_function()
32+
inputs = list(map(int, s.split(' ')))
33+
except Exception as e:
34+
print(e)
35+
else:
36+
sorted_input = quick_sort(inputs, 0, len(inputs) - 1)
37+
print('\nSorted list (min to max): {}'.format(sorted_input))
38+
39+
if __name__ == '__main__':
40+
print('==== Quick Sort ====\n')
41+
main()

‎README.md

Lines changed: 89 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,2 +1,89 @@
1-
# Python-
2-
All Algorithms implemented in Python
1+
# The Algorithms - Python
2+
3+
### All algorithms implemented in Python (for education)
4+
5+
These are for demonstration purposes only. There are many implementations of sorts in the Python standard library that are much better for performance reasons.
6+
7+
## Sorting Algorithms
8+
9+
### Binary
10+
Add comments here
11+
12+
### Bubble
13+
![alt text][bubble-image]
14+
15+
From [Wikipedia][bubble-wiki]: Bubble sort, sometimes referred to as sinking sort, is a simple sorting algorithm that repeatedly steps through the list to be sorted, compares each pair of adjacent items and swaps them if they are in the wrong order. The pass through the list is repeated until no swaps are needed, which indicates that the list is sorted.
16+
17+
__Properties__
18+
* Worst case performance O(n^2)
19+
* Best case performance O(n)
20+
* Average case performance O(n^2)
21+
22+
###### View the algorithm in [action][bubble-toptal]
23+
24+
25+
26+
### Insertion
27+
![alt text][insertion-image]
28+
29+
From [Wikipedia][insertion-wiki]: Insertion sort is a simple sorting algorithm that builds the final sorted array (or list) one item at a time. It is much less efficient on large lists than more advanced algorithms such as quicksort, heapsort, or merge sort.
30+
31+
__Properties__
32+
* Worst case performance O(n^2)
33+
* Best case performance O(n)
34+
* Average case performance O(n^2)
35+
36+
###### View the algorithm in [action][insertion-toptal]
37+
38+
39+
## Merge
40+
![alt text][merge-image]
41+
42+
From [Wikipedia][merge-wiki]: In computer science, merge sort (also commonly spelled mergesort) is an efficient, general-purpose, comparison-based sorting algorithm. Most implementations produce a stable sort, which means that the implementation preserves the input order of equal elements in the sorted output. Mergesort is a divide and conquer algorithm that was invented by John von Neumann in 1945.
43+
44+
__Properties__
45+
* Worst case performance O(n log n)
46+
* Best case performance O(n)
47+
* Average case performance O(n)
48+
49+
50+
###### View the algorithm in [action][merge-toptal]
51+
52+
## Quick
53+
![alt text][quick-image]
54+
55+
From [Wikipedia][quick-wiki]: Quicksort (sometimes called partition-exchange sort) is an efficient sorting algorithm, serving as a systematic method for placing the elements of an array in order.
56+
57+
__Properties__
58+
* Worst case performance O(n^2)
59+
* Best case performance O(n log n) or O(n) with three-way partition
60+
* Average case performance O(n^2)
61+
62+
###### View the algorithm in [action][quick-toptal]
63+
64+
65+
## Search Algorithms
66+
67+
### Linear
68+
Add comments here
69+
70+
## Ciphers
71+
72+
### Caesar
73+
Add comments here
74+
75+
[bubble-toptal]: https://www.toptal.com/developers/sorting-algorithms/bubble-sort
76+
[bubble-wiki]: https://en.wikipedia.org/wiki/Bubble_sort
77+
[bubble-image]: https://upload.wikimedia.org/wikipedia/commons/thumb/8/83/Bubblesort-edited-color.svg/220px-Bubblesort-edited-color.svg.png "Bubble Sort"
78+
79+
[insertion-toptal]: https://www.toptal.com/developers/sorting-algorithms/insertion-sort
80+
[insertion-wiki]: https://en.wikipedia.org/wiki/Insertion_sort
81+
[insertion-image]: https://upload.wikimedia.org/wikipedia/commons/7/7e/Insertionsort-edited.png "Insertion Sort"
82+
83+
[quick-toptal]: https://www.toptal.com/developers/sorting-algorithms/quick-sort
84+
[quick-wiki]: https://en.wikipedia.org/wiki/Quicksort
85+
[quick-image]: https://upload.wikimedia.org/wikipedia/commons/6/6a/Sorting_quicksort_anim.gif "Quick Sort"
86+
87+
[merge-toptal]: https://www.toptal.com/developers/sorting-algorithms/merge-sort
88+
[merge-wiki]: https://en.wikipedia.org/wiki/Merge_sort
89+
[merge-image]: https://upload.wikimedia.org/wikipedia/commons/c/cc/Merge-sort-example-300px.gif "Merge Sort"

‎SelectionSort.py

Lines changed: 0 additions & 20 deletions
This file was deleted.

‎binary_seach.py

Lines changed: 129 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,129 @@
1+
"""
2+
This is pure python implementation of binary search algorithm
3+
4+
For doctests run following command:
5+
python -m doctest -v selection_sort.py
6+
or
7+
python3 -m doctest -v selection_sort.py
8+
9+
For manual testing run:
10+
python binary_search.py
11+
"""
12+
from __future__ import print_function
13+
import bisect
14+
15+
16+
def assert_sorted(collection):
17+
"""Check if collection is sorted. If not raises :py:class:`ValueError`
18+
19+
:param collection: collection
20+
:return: True if collection is sorted
21+
:raise: :py:class:`ValueError` if collection is not sorted
22+
23+
Examples:
24+
>>> assert_sorted([0, 1, 2, 4])
25+
True
26+
27+
>>> assert_sorted([10, -1, 5])
28+
Traceback (most recent call last):
29+
...
30+
ValueError: Collection must be sorted
31+
"""
32+
if collection != sorted(collection):
33+
raise ValueError('Collection must be sorted')
34+
return True
35+
36+
37+
def binary_search(sorted_collection, item):
38+
"""Pure implementation of binary search algorithm in Python
39+
40+
:param sorted_collection: some sorted collection with comparable items
41+
:param item: item value to search
42+
:return: index of found item or None if item is not found
43+
44+
Examples:
45+
>>> binary_search([0, 5, 7, 10, 15], 0)
46+
0
47+
48+
>>> binary_search([0, 5, 7, 10, 15], 15)
49+
4
50+
51+
>>> binary_search([0, 5, 7, 10, 15], 5)
52+
1
53+
54+
>>> binary_search([0, 5, 7, 10, 15], 6)
55+
56+
>>> binary_search([5, 2, 1, 5], 2)
57+
Traceback (most recent call last):
58+
...
59+
ValueError: Collection must be sorted
60+
"""
61+
assert_sorted(sorted_collection)
62+
left = 0
63+
right = len(sorted_collection) - 1
64+
65+
while left <= right:
66+
midpoint = (left + right) // 2
67+
current_item = sorted_collection[midpoint]
68+
if current_item == item:
69+
return midpoint
70+
else:
71+
if item < current_item:
72+
right = midpoint - 1
73+
else:
74+
left = midpoint + 1
75+
return None
76+
77+
78+
def binary_search_std_lib(sorted_collection, item):
79+
"""Pure implementation of binary search algorithm in Python using stdlib
80+
81+
:param sorted_collection: some sorted collection with comparable items
82+
:param item: item value to search
83+
:return: index of found item or None if item is not found
84+
85+
Examples:
86+
>>> binary_search_std_lib([0, 5, 7, 10, 15], 0)
87+
0
88+
89+
>>> binary_search_std_lib([0, 5, 7, 10, 15], 15)
90+
4
91+
92+
>>> binary_search_std_lib([0, 5, 7, 10, 15], 5)
93+
1
94+
95+
>>> binary_search_std_lib([0, 5, 7, 10, 15], 6)
96+
97+
>>> binary_search_std_lib([5, 2, 1, 5], 2)
98+
Traceback (most recent call last):
99+
...
100+
ValueError: Collection must be sorted
101+
"""
102+
assert_sorted(sorted_collection)
103+
index = bisect.bisect_left(sorted_collection, item)
104+
if index != len(sorted_collection) and sorted_collection[index] == item:
105+
return index
106+
return None
107+
108+
109+
if __name__ == '__main__':
110+
import sys
111+
# For python 2.x and 3.x compatibility: 3.x has not raw_input builtin
112+
# otherwise 2.x's input builtin function is too "smart"
113+
if sys.version_info.major < 3:
114+
input_function = raw_input
115+
else:
116+
input_function = input
117+
118+
user_input = input_function('Enter numbers separated by coma:\n')
119+
collection = [int(item) for item in user_input.split(',')]
120+
121+
target_input = input_function(
122+
'Enter a single number to be found in the list:\n'
123+
)
124+
target = int(target_input)
125+
result = binary_search(collection, target)
126+
if result is not None:
127+
print('{} found at positions: {}'.format(target, result))
128+
else:
129+
print('Not found')

‎selection_sort.py

Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
"""
2+
This is pure python implementation of selection sort algorithm
3+
4+
For doctests run following command:
5+
python -m doctest -v selection_sort.py
6+
or
7+
python3 -m doctest -v selection_sort.py
8+
"""
9+
from __future__ import print_function
10+
11+
def selection_sort(sortable):
12+
"""Pure implementation of selection sort algorithm in Python
13+
14+
Examples:
15+
>>> selection_sort([0, 5, 3, 2, 2])
16+
[0, 2, 2, 3, 5]
17+
18+
>>> selection_sort([])
19+
[]
20+
21+
>>> selection_sort([-2, -5, -45])
22+
[-45, -5, -2]
23+
24+
:param sortable: some mutable ordered collection with heterogeneous
25+
comparable items inside
26+
:return: the same collection ordered by ascending
27+
"""
28+
length = len(sortable)
29+
for i in range(length):
30+
least = i
31+
for k in range(i + 1, length):
32+
if sortable[k] < sortable[least]:
33+
least = k
34+
sortable[least], sortable[i] = (
35+
sortable[i], sortable[least]
36+
)
37+
return sortable
38+
39+
40+
if __name__ == '__main__':
41+
import sys
42+
# For python 2.x and 3.x compatibility: 3.x has not raw_input builtin
43+
# otherwise 2.x's input builtin function is too "smart"
44+
if sys.version_info.major < 3:
45+
input_function = raw_input
46+
else:
47+
input_function = input
48+
49+
user_input = input_function('Enter numbers separated by coma:\n')
50+
unsorted = [int(item) for item in user_input.split(',')]
51+
print(selection_sort(unsorted))

0 commit comments

Comments
 (0)
Please sign in to comment.