Skip to content

Commit

Permalink
documentation
Browse files Browse the repository at this point in the history
  • Loading branch information
strongSoda committed Oct 19, 2019
1 parent 2cc8849 commit 781482d
Show file tree
Hide file tree
Showing 15 changed files with 650 additions and 156 deletions.
130 changes: 70 additions & 60 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -77,79 +77,89 @@ print(quick.__doc__)
Output:

```markdown
Quick Sort Implementation
Takes in an array & returns the sorted array
Quick sort is a highly efficient sorting algorithm and is based on partitioning of array of data
into smaller arrays. A large array is partitioned into two arrays one of which holds values
smaller than the specified value, say pivot, based on which the partition is made and another
array holds values greater than the pivot value.

## Documentation
Quick sort partitions an array and then calls itself recursively twice to sort the two resulting
subarrays. This algorithm is quite efficient for large-sized data sets as its average and worst
case complexity are of Ο(n2), where n is the number of items.

**Task**
### Quick Sort Pivot Algorithm

Sort an array (or list) elements using the quicksort algorithm.
Based on our understanding of partitioning in quick sort, we will now try to write an algorithm for
it, which is as follows.

The elements must have a strict weak order and the index of the array can be of any discrete type.
Step 1 − Choose the highest index value has pivot
Step 2 − Take two variables to point left and right of the list excluding pivot
Step 3 − left points to the low index
Step 4 − right points to the high
Step 5 − while value at left is less than pivot move right
Step 6 − while value at right is greater than pivot move left
Step 7 − if both step 5 and step 6 does not match swap left and right
Step 8 − if left ≥ right, the point where they met is new pivot

For languages where this is not possible, sort an array of integers.
### Quick Sort Pivot Pseudocode

The pseudocode for the above algorithm can be derived as −

Quicksort, also known as partition-exchange sort, uses these steps.

- Choose any element of the array to be the pivot.
- Divide all other elements (except the pivot) into two partitions.
- All elements less than the pivot must be in the first partition.
- All elements greater than the pivot must be in the second partition.
- Use recursion to sort both partitions.
- Join the first sorted partition, the pivot, and the second sorted partition.

The best pivot creates partitions of equal length (or lengths differing by 1).

The worst pivot creates an empty partition (for example, if the pivot is the first or last element of a sorted array).

The run-time of Quicksort ranges from O(n log n) with the best pivots, to O(n2) with the worst pivots, where n is the number of elements in the array.


This is a simple quicksort algorithm, adapted from Wikipedia.

function quicksort(array)
less, equal, greater := three empty arrays
if length(array) > 1
pivot := select any element of array
for each x in array
if x < pivot then add x to less
if x = pivot then add x to equal
if x > pivot then add x to greater
quicksort(less)
quicksort(greater)
array := concatenate(less, equal, greater)

A better quicksort algorithm works in place, by swapping elements within the array, to avoid the memory allocation of more arrays.
```python
function partitionFunc(left, right, pivot)
leftPointer = left
rightPointer = right - 1

while True do
while A[++leftPointer] < pivot do
//do-nothing
end while

while rightPointer > 0 && A[--rightPointer] > pivot do
//do-nothing
end while

if leftPointer >= rightPointer
break
else
swap leftPointer,rightPointer
end if

end while

swap leftPointer,right
return leftPointer

end function
```

### Quick Sort Algorithm

function quicksort(array)
if length(array) > 1
pivot := select any element of array
left := first index of array
right := last index of array
while left ≤ right
while array[left] < pivot
left := left + 1
while array[right] > pivot
right := right - 1
if left ≤ right
swap array[left] with array[right]
left := left + 1
right := right - 1
quicksort(array from first index to right)
quicksort(array from left to last index)
Using pivot algorithm recursively, we end up with smaller possible partitions. Each partition is
then processed for quick sort. We define recursive algorithm for quicksort as follows −

Quicksort has a reputation as the fastest sort. Optimized variants of quicksort are common features of many languages and libraries. One often contrasts quicksort with merge sort, because both sorts have an average time of O(n log n).
Step 1 − Make the right-most index value pivot
Step 2 − partition the array using pivot value
Step 3 − quicksort left partition recursively
Step 4 − quicksort right partition recursively

"On average, mergesort does fewer comparisons than quicksort, so it may be better when complicated comparison routines are used. Mergesort also takes advantage of pre-existing order, so it would be favored for using sort() to merge several sorted arrays. On the other hand, quicksort is often faster for small arrays, and on arrays of a few distinct values, repeated many times." — http://perldoc.perl.org/sort.html
Quicksort is at one end of the spectrum of divide-and-conquer algorithms, with merge sort at the opposite end.
### Quick Sort Pseudocode

Quicksort is a conquer-then-divide algorithm, which does most of the work during the partitioning and the recursive calls. The subsequent reassembly of the sorted partitions involves trivial effort.
Merge sort is a divide-then-conquer algorithm. The partioning happens in a trivial way, by splitting the input array in half. Most of the work happens during the recursive calls and the merge phase.
To get more into it, let see the pseudocode for quick sort algorithm −

With quicksort, every element in the first partition is less than or equal to every element in the second partition. Therefore, the merge phase of quicksort is so trivial that it needs no mention!
```python
procedure quickSort(left, right)

if right-left <= 0
return
else
pivot = A[right]
partition = partitionFunc(left, right, pivot)
quickSort(left,partition-1)
quickSort(partition+1,right)
end if

end procedure
```
```
### For Analysis
Expand Down
20 changes: 18 additions & 2 deletions gopy/sorting/bogo.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,21 @@
"""Bogo Sort Implementation
Takes in an array & returns the sorted array
"""
BogoSort also known as permutation sort, stupid sort, slow sort, shotgun sort or
monkey sort is a particularly ineffective algorithm based on generate and test
paradigm. The algorithm successively generates permutations of its input until
it finds one that is sorted.
For example, if bogosort is used to sort a deck of cards, it would consist of
checking if the deck were in order, and if it were not, one would throw the
deck into the air, pick the cards up at random, and repeat the process until
the deck is sorted.
### Complexity
- Worst case time complexity: O((N+1)!)
- Average case time complexity: O((N+1)!)
- Best case time complexity: O(N)
- Space complexity: O(1)
"""
import random

Expand Down
36 changes: 34 additions & 2 deletions gopy/sorting/bubble.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,37 @@
"""Bubble Sort Implementation
Takes in an array & returns the sorted array
"""
Bubble Sort is a simple algorithm which is used to sort a given set of n elements
provided in form of an array with n number of elements. Bubble Sort compares all
the element one by one and sort them based on their values.
If the given array has to be sorted in ascending order, then bubble sort will start
by comparing the first element of the array with the second element, if the first
element is greater than the second element, it will swap both the elements, and then
move on to compare the second and the third element, and so on.
If we have total n elements, then we need to repeat this process for n-1 times.
It is known as bubble sort, because with every complete iteration the largest element
in the given array, bubbles up towards the last place or the highest index, just like
a water bubble rises up to the water surface.
Sorting takes place by stepping through all the elements one-by-one and comparing it
with the adjacent element and swapping them if required.
### Implementing Bubble Sort Algorithm
Following are the steps involved in bubble sort(for sorting a given array in ascending order):
- Starting with the first element(index = 0), compare the current element with the next element of the array.
- If the current element is greater than the next element of the array, swap them.
- If the current element is less than the next element, move to the next element. Repeat Step 1.
### Following are the Time and Space complexity for the Bubble Sort algorithm.
Worst Case Time Complexity [ Big-O ]: O(n2)
Best Case Time Complexity [Big-omega]: O(n)
Average Time Complexity [Big-theta]: O(n2)
Space Complexity: O(1)
"""
def sort(array):
for i in range(len(array)):
Expand Down
39 changes: 37 additions & 2 deletions gopy/sorting/bucket.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,40 @@
"""Bucket Sort Implementation
Takes in an array & returns the sorted array
"""
### What is Bucket Sort ?
Bucket sort is a comparison sort algorithm that operates on elements by dividing
them into different buckets and then sorting these buckets individually. Each
bucket is sorted individually using a separate sorting algorithm or by applying
the bucket sort algorithm recursively. Bucket sort is mainly useful when the
input is uniformly distributed over a range.
#### Assume one has the following problem in front of them:
One has been given a large array of floating point integers lying uniformly
between the lower and upper bound. This array now needs to be sorted. A simple
way to solve this problem would be to use another sorting algorithm such as Merge
sort, Heap Sort or Quick Sort. However, these algorithms guarantee a best case
time complexity of O(NlogN). However, using bucket sort, the above task can be
completed in O(N) time.
```
void bucketSort(float[] a,int n)
{
for(each floating integer 'x' in n)
{
insert x into bucket[n*x];
}
for(each bucket)
{
sort(bucket);
}
}
```
### Time Complexity:
If one assumes that insertion in a bucket takes O(1) time, then steps 1 and 2 of the
above algorithm clearly take O(n) time.
"""
def bucket_sort(array):
largest = max(array)
Expand Down
23 changes: 21 additions & 2 deletions gopy/sorting/cocktail.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,24 @@
"""Cocktail Shaker Sort Implementation
Takes in an array & returns the sorted array
"""
Cocktail sort is the variation of Bubble Sort which traverses the list in both
directions alternatively. It is different from bubble sort in the sense that,
bubble sort traverses the list in forward direction only, while this algorithm
traverses in forward as well as backward direction in one iteration.
### Algorithm
In cocktail sort, one iteration consists of two stages:
- The first stage loop through the array like bubble sort from left to right. The adjacent elements are compared and if left element is greater than the right element, then we swap those elements. The largest element of the list is placed at the end of the array in the forward pass.
- The second stage loop through the array from the right most unsorted element to the left. The adjacent elements are compared and if right element is smaller than the left element then, we swap those elements. The smallest element of the list is placed at the beginning of the array in backward pass.
The process continues until the list becomes unsorted.
### Complexity
**Complexity** **Best Case** **Average Case** **Worst Case**
**Time Complexity** O(n2) O(n2) O(n2)
**Space Complexity** O(1) O(1) O(1)
"""
def cocktail_shaker_sort(array):
def swap(i, j):
Expand Down
50 changes: 48 additions & 2 deletions gopy/sorting/comb.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,51 @@
"""Comb Sort Implementation
Takes in an array & returns the sorted array
"""
The basic idea of comb sort and the bubble sort is same. In other words,
comb sort is an improvement on the bubble sort. In the bubble sorting
technique, the items are compared with the next item in each phase. But
for the comb sort, the items are sorted in a specific gap. After completing
each phase, the gap is decreased. The decreasing factor or the shrink factor
for this sort is 1.3. It means that after completing each phase the gap is
divided by 1.3.
### The complexity of Comb Sort Technique
- Time Complexity: O(n log n) for the best case. O(n^2/2^p) (p is a number of increment)
for average case and O(n^2) for the worst case.
- Space Complexity: O(1)
### Input and Output
Input:
A list of unsorted data: 108 96 23 74 12 56 85 42 13 47
Output:
Array before Sorting: 108 96 23 74 12 56 85 42 13 47
Array after Sorting: 12 13 23 42 47 56 74 85 96 108
### Algorithm
CombSort(array, size)
Input: An array of data, and the total number in the array
Output: The sorted Array
Begin
gap := size
flag := true
while the gap ≠ 1 OR flag = true do
gap = floor(gap/1.3) //the the floor value after division
if gap < 1 then
gap := 1
flag = false
for i := 0 to size – gap -1 do
if array[i] > array[i+gap] then
swap array[i] with array[i+gap]
flag = true;
done
done
End
"""
def comb_sort(array):
def swap(i, j):
Expand Down
29 changes: 27 additions & 2 deletions gopy/sorting/counting.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,30 @@
"""Counting Sort Implementation
Takes in an array & returns the sorted array
"""
Counting sort is an efficient algorithm for sorting an array of elements that each have
a nonnegative integer key, for example, an array, sometimes called a list, of positive
integers could have keys that are just the value of the integer as the key, or a list
of words could have keys assigned to them by some scheme mapping the alphabet to
integers (to sort in alphabetical order, for instance). Unlike other sorting algorithms,
such as mergesort, counting sort is an integer sorting algorithm, not a comparison based
algorithm. While any comparison based sorting algorithm requires Omega(nlgn)Ω(nlgn)
comparisons, counting sort has a running time of Theta(n)Θ(n) when the length of the
input list is not much smaller than the largest key value, kk, in the list. Counting
sort can be used as a subroutine for other, more powerful, sorting algorithms such as
radix sort
### Complexity of Counting Sort
Counting sort has a O(k+n)O(k+n) running time.
The first loop goes through AA, which has nn elements. This step has a O(n)O(n) running
time. The second loop iterates over kk, so this step has a running time of O(k)O(k). The
third loop iterates through AA, so again, this has a running time of O(n)O(n). Therefore,
the counting sort algorithm has a running time of O(k+n)O(k+n).
Counting sort is efficient if the range of input data, kk, is not significantly greater
than the number of objects to be sorted, nn.
Counting sort is a stable sort with a space complexity of **O(k + n)O(k+n).**
"""
def counting_sort(array, largest):
c = [0]*(largest + 1)
Expand Down
21 changes: 19 additions & 2 deletions gopy/sorting/gnome.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,22 @@
"""Gnome Sort Implementation
Takes in an array & returns the sorted array
"""
The simplest sort algorithm is not Bubble Sort..., it is not Insertion Sort..., it's Gnome Sort!
Gnome Sort is based on the technique used by the standard Dutch Garden Gnome (Du.: tuinkabouter).
Here is how a garden gnome sorts a line of flower pots. Basically, he looks at the flower pot
next to him and the previous one; if they are in the right order he steps one pot forward,
otherwise he swaps them and steps one pot backwards. Boundary conditions: if there is no
previous pot, he steps forwards; if there is no pot next to him, he is done.
```C
void gnomesort(int n, int ar[]) {
int i = 0;
while (i < n) {
if (i == 0 || ar[i-1] <= ar[i]) i++;
else {int tmp = ar[i]; ar[i] = ar[i-1]; ar[--i] = tmp;}
}
}
```
"""
def gnome_sort(array):
for pos in range(1, len(array)):
Expand Down
Loading

0 comments on commit 781482d

Please sign in to comment.