I will talk about two different sorting method and a way of searching.

# Selection Sort

When we have an array of random numbers, for example

450 604 100 802 301 200
[0] [1] [2] [3] [4] [5]


Let’s find the smallest number first, which is 100, and then swap it with number in [0].

100 | 604 450 802 301 200
[0] | [1] [2] [3] [4] [5]


In this case, we have a sorted array on the left and an unsorted array on the right. We seperate those two arrays by a line.

Secondly, we find the minimum number from the array on the right and swap it with number in [1].

100 200 | 450 802 301 604
[0] [1] | [2] [3] [4] [5]


Finally, we just kepp repeating this step until there isn’t any element in the right array.

100 200 301 | 802 450 604
[0] [1] [2] | [3] [4] [5]

100 200 301 450 | 802 604
[0] [1] [2] [3] | [4] [5]

100 200 301 450 604 | 802
[0] [1] [2] [3] [4] | [5]

100 200 301 450 604 802 |
[0] [1] [2] [3] [4] [5] |


# Insertion Sort

In this method, we treat number in [0] as a sorted array

450 | 604 100 802 301 200
[0] | [1] [2] [3] [4] [5]


Then we compare numbers in [0] and in [1]. Insert the number in [1] if it is smaller

100 604 | 450 802 301 200
[0] [1] | [2] [3] [4] [5]


Secondly, we compare 450 with each number and insert it into the correct position

100 450 604 | 802 301 200
[0] [1] [2] | [3] [4] [5]


Finally, we just keep repeating this step until there isn’t any element in the right array.

100 450 604 802 | 301 200
[0] [1] [2] [3] | [4] [5]

100 301 450 604 802 | 200
[0] [1] [2] [3] [4] | [5]

100 200 301 450 604 802 |
[0] [1] [2] [3] [4] [5] |


# Binary Search

In order to search an object, we need to sort the original array first. So we assume what binary search deal with is a sorted list. For example, we want to find 500 in following array,

100 200 300 400 500 600
[0] [1] [2] [3] [4] [5]


We divide this array into two halves and compare 500 with the last element in the first half.

100 200 300 | 400 500 600
[0] [1] [2] | [3] [4] [5]

300<500


Clearly, 500 is not in the first half, then we divide the second half into two parts and compare again.

100 200 300 |    400 500 | 600
[0] [1] [2] |    [3] [4] | [5]

500==500


That’s how we find 500 in the array. Obviously, it is faster than compare 500 with elements in the array one by one.