ch10 readme and 2 exercises

This commit is contained in:
anebz 2020-10-09 15:57:30 +02:00
parent c4749bc3aa
commit f52d0cde54
4 changed files with 172 additions and 1 deletions

View File

@ -0,0 +1,42 @@
# 10.1. Sorted merge
> You have 2 sorted arrays A and B, and A has a large enough buffer at the end to hold B. Merge B into A in a sorted order
```python
def merge_arrays(a: list, b: list):
'''
a = [1, 3, 4, 6]
b = [2, 5]
'''
idx = 0
b_pos = 0
while b_pos < len(b):
while a[idx] < b[b_pos]:
idx += 1
a.insert(b[b_pos], idx)
b_pos += 1
```
This would take O(n) for worst case scenario, where n=len(A), O(m) in best case scenario for m=len(B). Space complexity O(1) because we can store this info in A directly.
## Solution
Simply compare elements of A and B and insert them in order. The only problem is that if we insert an element in the front of A, then we have to shift the existing elements to the back. It's better to insert elements into the back of the array, where there is empty space.
```python
def merge(a, b, lastA, lastB):
indexA = lastA - 1
indexB = lastB - 1
indexMerged = lastA + lastB - 1
while indexB >= 0:
# end of A is > than end of B
if indexA >= 0 and a[indexA] > b[indexB]:
a[indexMerged] = a[indexA]
indexA -= 1
else:
a[indexMerged] = b[indexB]
indexB -= 1
indexMerged -= 1
return
```

View File

@ -0,0 +1,40 @@
# 10.2. Anagrams
> Sort an array of strings so that all the anagrams are next to each other.
Anagram: word formed by rearranging the letters of another, such as spar formed by rasp.
Each word in the array should be sorted alphabetically, and then each word sorted in the array. Can start from the beginning, sort each word, and iteratively add the new sorted word to the sorted array.
```c++
const int MAX_CHAR = 26;
// function to print string in sorted order
void sortString(string &str) {
// Hash array to keep count of characters.
// Initially count of all charters is
// initialized to zero.
int charCount[MAX_CHAR] = {0};
// Traverse string and increment
// count of characters
for (int i=0; i<str.length(); i++)
// 'a'-'a' will be 0, 'b'-'a' will be 1,
// so for location of character in count
// array we wil do str[i]-'a'.
charCount[str[i]-'a']++;
// Traverse the hash array and print
// characters
for (int i=0; i<MAX_CHAR; i++)
for (int j=0; j<charCount[i]; j++)
cout << (char)('a'+i);
}
```
which takes O(n) time and O(1) space for each word. Then, we need to group the strings in the array by anagram.
## Solution
Use a hash table mapping the sorted version of a word to a list of anagrams. `acre` maps to `{acre, race, care}`. Once we have grouped all the words into these lists by anagram, we can then put them back into the array. This is an adaptation of **bucket sort**.

View File

@ -0,0 +1,82 @@
# 10. Sorting and searching
## Sorting algorithms
### Bubble sort
> Runtime O(n<sup>2</sup>) average and worst case. Memory O(1)
Start at the beginning, swap the first two elements if the first is greater than the second. Go to the next pair and repeat, and so on until reaching the end of the array.
### Selection sort
> Runtime O(n<sup>2</sup>) average and worst case. Memory O(1)
Simple but inefficient. Find the smallest element using a linear scan, move it to the front, swapping it with the first element. Then, find the second smallest and move it, doing a linear scan. And so on
### Merge sort
> Runtime O(n log(n)) average and worst case. Memory depends, usually O(n)
Divides the array in half, sort each of these halves, merge them back together. Eventually, you merge just the two single-element arrays, and the merge part does all the heavy lifting.
When merging, copy all the elements from the target array segment into a helper array, when iterating through helper, copy the smaller element from each half into the array. At the end, copy any remaining elements into the target array.
Java algorithm in book.
### Quick sort
> Runtime O(n log(n)) average, O(n<sup>2</sup>) worst case. Memory O(n log(n))
Pick a random element and partition the array, such that all numbers lower than the partitioning element come before all elements greater than it. Repeatedly partitioning the array (and its sub-arrays) around an element, the array is eventually sorted. But as the partitioned element is not guaranteed to be the median or close to it, the sorting could be very slow. That is why the worst case rutime is O(n<sup>2</sup>).
```python
a = [3, 5, 2, 4, 1, 6, 7], left=0, right=6
pivot = a[3] = 4
left = 1
right = 4
swap a
a = [3, 1, 2, 4, 5, 6, 7]
left = 2
right = 3
next loop of big while
left = 3
right = 3
swap a
remains the same because left=right
left = 4
right = 2
break big loop, return 4 -> index=4
left=0 < index-1=3, so quicksort the left half
index=4 < right=6, so quicksort the right half
```
### Radix sort
> Runtime O(kn)
Sorting algorithm for integers that takes advantage of the fact that integers have a finite number of bits. We iterate through each digit of the number, grouping numbers by each digit. With an array of integers, we might sort by the first digit, so that the 0s are grouped together, then sort by the next digit.
N is the number of elements and k is the number of passes of the sorting algorithm.
### [Bucket sort](https://en.wikipedia.org/wiki/Bucket_sort)
> Runtime O(n<sup>2</sup>) worst case, O(n + n<sup>2</sup>/k + k) where k is the number of buckets, average performance. Worst-case space complexity is O(nk)
This is a sorting algorithm that distributes the elements of an array into a number of buckets. Each bucket is sorted individually, either using a different sorting algorithm or by recursively applying the bucket sorting algorithm.
## Searching algorithms
In **binary search**, we look for an element x in a sorted array by first comparing x to the midpoint of the array. If x is lower, we search the left half. and vice versa.
See code in book.
There are more algorithms than just binary search, use binary trees or hash tables too.

View File

@ -72,7 +72,7 @@ If you can't afford to buy the book, you can find a free pdf [here](http://ahmed
* Triple step
* Robot in grid
* Magic index (index such that A[i] = 1)
* Magic index (index such that A\[i\] = 1)
* Power set
* Permutations of string with unique characters
* Permutations of string with duplicate characters
@ -82,9 +82,16 @@ If you can't afford to buy the book, you can find a free pdf [here](http://ahmed
* Stock data
* Social network
* Web crawler
* Duplicate URLs
* Cache
* Sales rank
* Personal finance manager
## Chapter 10 Sorting and searching
* Sorted merge
* Anagrams
* Search in rotated array
* Sorted matrix search
## Chapter 16 Moderate problems