DEV Community

Cover image for A Short Intro to Algorithms
csamanta95
csamanta95

Posted on

A Short Intro to Algorithms

An algorithms in the simplest definition is a solution to a problem. Algorithms are a set of guidelines that describe how to solve a problem and perform a task.

A great place to start is by learning the search and sorting algorithms. The linear sort is one the simplest search algorithms. The algorithm below is the linear search: compares the key (item to find) to each item in a list until it has been found.

Linear Sort in Ruby

Linear Sort in Ruby

What the algorithm is doing:
1) The method "linear_search" takes in an array and a key. The key is the item you’re looking for. The algorithm starts from the leftmost element of the array and one by one compares the element we are searching for with each element of the array.
2) If the key is not found, a message is returned.
3) If the key is found, a message is printed out stating the key and the index.

Linear Sort in Ruby: Solution

Bubble Sort is the simplest sorting algorithm that works by repeatedly swapping the adjacent elements if they are in wrong order. The algorithm below is the bubble sort: sorts an array in ascending order.

Bubble Sort in Ruby: Solution

Bubble Sort in Ruby: Solution

What the algorithm is doing:
1) The method "bubbleSort" takes in a single array parameter.
2) A variable "n" finds the array length. Bubble sort needs to know the length in order to know how many times to iterate through the array.
3) The "loop do" will loop through then iterate through each element of the array. With "loop do" in ruby, you need to tell the method when to stop. The sentinel variable "swapped" will let the loop know when to stop. Swapped = false is set in the beginning since immediately after the beginning of your loop, there have been no swaps. Swapped will break when it can no longer be true (there are no more swapping needed). The loop will run as long as the swap is true.
4)The loop will check if element i is greater than the element next to it i + 1. If it is, it will swap the value of i with the value of i+1. The loop will also set the value of swapped to true when there is a swap made.

Bubble Sort in Ruby: Solution

5)The loop will terminate when there is no more swaps needed and the array will be returned in ascending order.

Bubble Sort in Ruby: Solution

Top comments (0)