# Algorithms

Yesterday I was watching the brilliantly written Silicon Valley from HBO. The show is built around something that’s been close to my heart (or server) recently – algorithms. (I had the joy of turning in a search algorithm and taking a test over how to work with Minimum-Spanning Trees this week.)

I won’t touch on how any specific algorithms work because that can get very tedious and boring. So this post will focus on three of the most important methods and properties of algorithms.

1.Iteration

In order to reach every element in a set of values (or at least the ones we want to reach), we need to have a method of moving from one value to the next. It seems basic, but some of these implementations can get a little bit tricky. There are two basic methods of iterating through material.

The first is a ‘For Loop.” A “For Loop” uses a counter to access each value, increasing the counter to reach the next value.

For example, if “Array” is a set of 10 values, we could access the first value in Array by typing “Array[0]”. To access the rest of the values, we would simply iterate the value by one.

for(i = 0; i <= 9; i++)

print “array[0]”

The other method of iteration is attaching a ‘next’ pointer to every value that points to the next value and setting the final value to point to NULL. When it reaches NULL, the iteration will end.

while(value!=NULL)

value = value->next

2. Recursion

Recursion is an abstract process that allows a program to reach the next value by sending the next value into the same function a second time. It can become very difficult to comprehend. Hopefully this video will help you understand. Explaining it through text simply won’t do it justice.

3. Swapping

The third topic is the main operation of most sorting algorithms. The idea of swapping is to move values around into the order in which the programmer wants them. One of swapping’s most basic implementations is inside of a bubble sort. A bubble sort can take an array of values and move them until they are in sorted order. That is, it can take 6 7 3 4 5 8 9 10 1 2 and turn it into 1 2 3 4 5 6 7 8 9 10.

The code to accomplish a sort of that nature looks something like this:

- i is a counter

- j is a counter

- n is the number of values inside of the array

- temporary holds the value that is being swapped.

for(i = 0; i < n; i++)

{

for(j = 0; j<n-1;j++)

{

temporary value = array[j+1]

array[j + 1] = array[j]

array[j] = temporary value

}

}

If you want to watch the entire first episode of Silicon Valley, HBO was kind enough to put it on YouTube