Skip to content

Commit

Permalink
initiated recursion
Browse files Browse the repository at this point in the history
  • Loading branch information
gaurav1780 committed Sep 4, 2018
1 parent 94dc7fe commit a82ed73
Show file tree
Hide file tree
Showing 9 changed files with 277 additions and 38 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -79,7 +79,7 @@ public static boolean containsDuplicateSorted(int[] data) {

### Example 2

Finding if two items have the same items is much easier if you sort the arrays and them compare for them being identical.
Finding if two arrays have the same items is much easier if you sort the arrays and them compare for them being identical.

>{10, 40, 20, 90} and {90, 20, 10, 40} have the same items
Expand All @@ -92,7 +92,7 @@ public static boolean sameItemsUnsorted(int[] a, int[] b) {
if(a.length != b.length)
return false;
for(int i=0; i < a.length; i++) {
if(count(a, a[i]) != count(b, a[i]) {
if(count(a, a[i]) != count(b, a[i])) {
return false;
}
}
Expand All @@ -114,7 +114,7 @@ public static int count(int[] data, int item) {
#### Solution with sorted arrays :)

```
public static boolean sameItemsUnsorted(int[] a, int[] b) {
public static boolean sameItemsSorted(int[] a, int[] b) {
if(a.length != b.length)
return false;
for(int i=0; i < a.length; i++) {
Expand All @@ -126,6 +126,61 @@ public static boolean sameItemsUnsorted(int[] a, int[] b) {
}
```

**Case 1**: Comparing `{10, 70, 20, 90}` with `{10, 70, 20, 90}`

>Compare first items
>
><span style="color:green">10</span> 70 20 90
>
><span style="color:green">10</span> 70 20 90
<p>&nbsp;</p>

>Compare second items
>
>10 <span style="color:green">70</span> 20 90
>
>10 <span style="color:green">70</span> 20 90
<p>&nbsp;</p>

>Compare third items
>
>10 70 <span style="color:green">20</span> 90
>
>10 70 <span style="color:green">20</span> 90
<p>&nbsp;</p>

>Compare fourth items
>
>10 70 20 <span style="color:green">90</span>
>
>10 70 20 <span style="color:green">90</span>
<p>&nbsp;</p>

>return `true`
**Case 2**: Comparing `{10, 70, 20, 90}` with `{10, 80, 20, 90}`

>Compare first items
>
><span style="color:green">10</span> 70 20 90
>
><span style="color:green">10</span> 80 20 90
<p>&nbsp;</p>

>Compare second items
>
>10 <span style="color:red">70</span> 20 90
>
>10 <span style="color:red">80</span> 20 90
<p>&nbsp;</p>

>return `false`
{: challenge}
> ## Define a method that returns the highest number in an unsorted array. Return 0 if array is null or empty.
>> ## SOLUTION
Expand Down
34 changes: 34 additions & 0 deletions _collections/_04-searching-and-sorting/02-selection-sort.md
Original file line number Diff line number Diff line change
Expand Up @@ -116,6 +116,40 @@ public static int getSmallestItemIndex(int[] data, int firstIndex) {
}
```

Of course, you can have another version of the same using a `for` loop for the outside loop. But it's only a different coding style - the algorithm remains the same. Note that the implementarion of `getSmallestItemIndex` remains the same.

#### Variation 2

```java
public static void selectionSort(int[] arr) {
for(int startIndex = 0; startIndex < arr.length - 1; startIndex++) {
int smallestIndex = getSmallestItemIndex(arr, startIndex);

int temp = arr[startIndex];
arr[startIndex] = arr[smallestIndex];
arr[smallestIndex] = temp;
}
}
```

{: challenge}
> ## Modify the implementation of selection sort so it sorts the array in descending order.
>> ## SOLUTION
>>>```java
>>>public static void selectionSortDescending(int[] arr) {
>>> for(int startIndex = 0; startIndex < arr.length - 1; startIndex++) {
>>> int highestIndex = getHighestItemIndex(arr, startIndex); //ONLY CHANGE: find index of highest item
>>> //implementation of getHighestItemIndex left as homework exercise
>>>
>>> int temp = arr[startIndex];
>>> arr[startIndex] = arr[highestIndex];
>>> arr[highestIndex] = temp;
>>> }
>>>}
>>>```
>{: .solution}
{: .challenge}
## Selection sort performance
The number of times `getSmallestItemIndex` method is called is `(n-1)`.
Expand Down
58 changes: 48 additions & 10 deletions _collections/_04-searching-and-sorting/03-insertion-sort.md
Original file line number Diff line number Diff line change
Expand Up @@ -143,36 +143,74 @@ public static void insertionSort(int[] arr) {
int idx = 1;
while(idx < arr.length) {
int backup = arr[idx];
int k = i-1;
while(k >= 0 && arr[k] > backup) {
arr[k+1] = arr[k]; //move item forward
k--; //check item before it
int currentIndex = idx-1;
while(currentIndex >= 0 && arr[currentIndex] > backup) {
arr[currentIndex+1] = arr[currentIndex]; //move item forward
currentIndex--; //check item before it
}
arr[k+1] = backup; //move backup at index of last moved item
arr[currentIndex+1] = backup; //move backup at index of last moved item
idx++; //check for the next item
}
}
```

Of course, you can have another version of the same using a `for` loop for the outside loop. But it's only a different coding style - the algorithm remains the same.

#### Variation 2

```java
public static void insertionSort(int[] arr) {
for(int idx = 1; idx < arr.length; idx++) {
int backup = arr[idx];
int currentIndex = idx-1;
while(currentIndex >= 0 && arr[currentIndex] > backup) {
arr[currentIndex+1] = arr[currentIndex]; //move item forward
currentIndex--; //check item before it
}
arr[currentIndex+1] = backup; //move backup at index of last moved item
}
}cup
```

{: challenge}
> ## Modify the implementation of insertion sort so it sorts the array in descending order.
>> ## SOLUTION
>>>```java
>>>public static void insertionSortDescending(int[] arr) {
>>> for(int idx = 1; idx < arr.length; idx++) {
>>> int backup = arr[idx];
>>> int currentIndex = idx-1;
>>> while(currentIndex >= 0 && arr[currentIndex] < backup) { //ONLY CHANGE: smaller items to the end
>>> arr[currentIndex+1] = arr[currentIndex];
>>> currentIndex--;
>>> }
>>> arr[currentIndex+1] = backup;
>>> }
>>>}
>>>```
>{: .solution}
{: .challenge}
## Insertion sort performance
### Best case scenario
In the best case, the array is already sorted in ascending order. The boolean expression `(k >= 0 && arr[k] > backup)` is never true and the inner loop never executes.
In the best case, the array is already sorted in ascending order. The boolean expression `(currentIndex >= 0 && arr[currentIndex] > backup)` is never true and the inner loop never executes.
Thus, in the best case, there are `n-1` executions of the expression `(k >= 0 && arr[k] > backup)`
Thus, in the best case, there are `n-1` executions of the expression `(currentIndex >= 0 && arr[currentIndex] > backup)`
> Number of iterations in worst case: `n-1`
> Number of iterations in best case: `n-1`
### Worst case scenario
In the best case, the array is already sorted in ascending order. The boolean expression `(k >= 0 && arr[k] > backup)` is true for all `k >= 0`, the inner loop executes the following number of times:
In the best case, the array is already sorted in ascending order. The boolean expression `(currentIndex >= 0 && arr[currentIndex] > backup)` is true for all `currentIndex >= 0`, the inner loop executes the following number of times:
- 1 time, for `idx = 1`
- 2 times, for `idx = 2`
- ...
- `n-1` time, for `idx = arr.length - 1`
Thus, in the worst case, there are `1+2+...+n-1` = `n*(n-1)/2` executions of the expression `(k >= 0 && arr[k] > backup)`
Thus, in the worst case, there are `1+2+...+n-1` = `n*(n-1)/2` executions of the expression `(currentIndex >= 0 && arr[currentIndex] > backup)`
> Number of iterations in worst case: `n*(n-1)/2`
Expand Down
2 changes: 1 addition & 1 deletion _collections/_04-searching-and-sorting/04-binary-search.md
Original file line number Diff line number Diff line change
Expand Up @@ -127,7 +127,7 @@ What happens when `first > last` and the expression is no longer true? We have s
### Putting it all together

```java
public static int binarySearch(int[] arr) {
public static int binarySearch(int[] arr, int target) {
int first = 0;
int last = arr.length - 1;
while(first <= last) {
Expand Down
59 changes: 59 additions & 0 deletions _collections/_05-recursion/01-what-is-recursion.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
---
title: "What is recursion?"
---

# What is recursion?

There are two classical approaches to solving algorthmic problems:

1. Iterative
2. Recursive

## Iterative solution

The distinctive property of *iterative* solutions is that they do not reduce a problem to a simpler form of itself.

### EXAMPLE

Add all integers between `low` and `high` (inclusive on both sides, and assuming `low` <= `high`), I can go through each integer and add it to an accumulating variable, say `total`.

```java
public static int sum(int low, int high) {
if(low % 2 != 0) {
low++;
}
int total = 0;
for(int i=low; i<=high; i++) {
total = total + i;
}
return total;
}
```

## Recursive solution

The distinctive property of *recursive* solutions is that they reduce a problem to a simpler form of itself.

### EXAMPLE

For the same problem statement used for iterative solutions, we can say that the sum of all integers from `low` to `high` is:

```
if low <= high:
sub = sum of all integers from (low+1) to high
return (low + sub)
else
return 0
```

Focus on the part

>```
>sum of all integers from `low+1` to `high`
>```
It is the same problem as the original problem, except there is one less number to handle, and thus is *simpler*.
## Equivalence
It has been proven that there is a recursive solution for every iterative solution and vice versa. We will soon look at some of the aspects to consider while deciding on which approach to take.
53 changes: 53 additions & 0 deletions _collections/_05-recursion/02-why-do-i-need-recursion.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
---
title: "Motivation for searching and sorting algorithms"
---

# Why should I use recursion?

## Advantages

1. Some solutions have an intuitive recursive design. Some examples (we assume n >= 0 for all examples):

1. x<sup>n</sup> = x<sup>n-1</sup> * x (if n > 0, or 1 if n == 0)
2. `nDigits(n)` = `nDigits(n/10) + 1` (if n > 0, or 0 if n == 0)
3. `sum(n) = sum(n-1) + n` if(n > 0, or 0 if n == 0)

2.
>return `false`
{: challenge}
> ## Define a method that returns the highest number in an unsorted array. Return 0 if array is null or empty.
>> ## SOLUTION
>>> ```java
>>> public static int highestUnsorted(int[] arr) {
>>> if(arr == null || arr.length == 0) {
>>> return 0;
>>> }
>>> int result = arr[0];
>>> for(int i=1; i < arr.length; i++) {
>>> if(arr[i] > result) {
>>> result = arr[i];
>>> }
>>> }
>>> return result;
>>> }
>>> ```
>{: .solution}
{: .challenge}
{: challenge}
> ## Define a method that returns the highest number in an array sorted in ascending order. Return 0 if array is null or empty.
>> ## SOLUTION
>>> ```java
>>> public static int highestSorted(int[] arr) {
>>> if(arr == null || arr.length == 0) {
>>> return 0;
>>> }
>>> return arr[arr.length-1]; //last item is the highest item
>>> }
>>> ```
>{: .solution}
{: .challenge}
### Cost of sorting needs to be recognized
Of course, sorting involves a one-time fixed-cost of sorting the array, but the ongoing or variable cost of these operations reduces considerablly.
40 changes: 20 additions & 20 deletions _config.yml
Original file line number Diff line number Diff line change
Expand Up @@ -136,23 +136,23 @@ highlighter: rouge
markdown: kramdown
# !github-pages! mandatory › https://help.github.com/articles/using-jekyll-with-pages/#configuration-settings-you-cannot-change
# Since Jekyll 3 the default highlighter is Rouge (replaced Pygments.rb in v44)
highlighter: rouge

# More › http://kramdown.gettalong.org/quickref.html
# Options › http://kramdown.gettalong.org/options.html
kramdown:
input: GFM
# https://github.com/jekyll/jekyll/pull/4090
syntax_highlighter: rouge

# Rouge Highlighter in Kramdown › http://kramdown.gettalong.org/syntax_highlighter/rouge.html
# span, block element options fall back to global
syntax_highlighter_opts:
# Rouge Options › https://github.com/jneen/rouge#full-options
css_class: 'highlight'
#line_numbers: true # bad idea, spans don't need linenos and would inherit this option
span:
line_numbers: false
block:
line_numbers: true
start_line: 1
# highlighter: rouge
#
# # More › http://kramdown.gettalong.org/quickref.html
# # Options › http://kramdown.gettalong.org/options.html
# kramdown:
# input: GFM
# # https://github.com/jekyll/jekyll/pull/4090
# syntax_highlighter: rouge
#
# # Rouge Highlighter in Kramdown › http://kramdown.gettalong.org/syntax_highlighter/rouge.html
# # span, block element options fall back to global
# syntax_highlighter_opts:
# # Rouge Options › https://github.com/jneen/rouge#full-options
# css_class: 'highlight'
# #line_numbers: true # bad idea, spans don't need linenos and would inherit this option
# span:
# line_numbers: false
# block:
# line_numbers: true
# start_line: 1
2 changes: 1 addition & 1 deletion _data/navigation-list.yml
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@ navigation_list:
- title: Array of objects
link: 09-array-of-objects.html
- id: 04-searching-and-sorting
title: Week 5 - Searching And Sorting
title: Weeks 5, 6 - Searching And Sorting
links:
- title: Motivation for searching and sorting algorithms
link: 01-motivation-for-searching-sorting-algorithms.html
Expand Down
Loading

0 comments on commit a82ed73

Please sign in to comment.