Skip to content

Commit a819825

Browse files
author
Chris Pilcher
committed
Adding example to readme for minimum and maximum
1 parent e5c22d6 commit a819825

File tree

1 file changed

+20
-2
lines changed

1 file changed

+20
-2
lines changed

Select Minimum Maximum/README.markdown

Lines changed: 20 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2,10 +2,10 @@
22

33
Goal: Find the minimum/maximum object in an unsorted array.
44

5-
We have an array of generic objects and we iterate over all the objects keeping track of the minimum/maximum element so far.
6-
75
### Maximum or minimum
86

7+
We have an array of generic objects and we iterate over all the objects keeping track of the minimum/maximum element so far.
8+
99
#### An example
1010

1111
Let's say the we want to find the maximum value in the unsorted list `[ 8, 3, 9, 4, 6 ]`.
@@ -52,6 +52,24 @@ maximum(array) // This will return 9
5252

5353
To find both the maximum and minimum values contained in array while minimizing the number of comparisons we can compare the items in pairs.
5454

55+
#### An example
56+
57+
Let's say the we want to find the minimum and maximum value in the unsorted list `[ 8, 3, 9, 4, 6 ]`.
58+
59+
Pick the first number, `8`, and store it as the minimum and maximum element so far.
60+
61+
Because we have an odd number of items we remove `8` from the list which leaves the pairs `[ 3, 9 ]` and `[ 4, 6 ]`.
62+
63+
Pick the next pair of numbers from the list, `[ 3, 9 ]`, `3` is less than `9` so we compare `3` to the current minimum `8` and `9` to the current maximum `8`. `3` is less than `8` so the new minimum is `3`. `9` is greater than `8` so the new maximum is `9`.
64+
65+
Pick the next pair of numbers from the list, `[ 4, 6 ]`, `4` is less than `6` so we compare `4` to the current minimum `3` and `6` to the current maximum `9`. `4` is greater than `3` so the minimum does not change. `6` is less than `9` so the maximum does not change.
66+
67+
The result is a minimum of `2` and a maximum of `9`.
68+
69+
#### The code
70+
71+
Here is a simple implementation in Swift:
72+
5573
```swift
5674
func minimumMaximum<T: Comparable>(var array: [T]) -> (minimum: T, maximum: T)
5775
{

0 commit comments

Comments
 (0)