Part 7

# Algorithms

Algorithms, precise instructions on how to to accomplish a specific task, are at the core of computer science. In the context of programming, algorithms are typically defined using source code.

The concept of efficiency is often associated with algorithms. A programs efficiency, i.e, the computation of required information fast enough, is an integral part of a programs usability. If it took two days for an algorithm designed for forecasting tomorrows weather run, the results wouldn't be very useful! Similarly, a user viewing a TVs program guide won't get any use out of it, if the tv-shows info only loads after the show already ended.

In a more general sense, retrieving and displaying information quickly is an integral part of any applications function. Next let's explore algorithms associated with retrieving and sorting information. While the following examples utilize arrays, the algorithms shown will also work with other data-structures meant for storing information, such as lists.

## Sorting information

If the information (data) giving to a computer, doesn't follow any rules and isn't in order, retrieving that information is taxing for the computer. We need order!

### Selection sort

Every programmer should be familiar with at least one sorting algorithm (i.e a way to sort an array). Let's familiarize ourselves with one "classic" sorting algorithm, the selection sort. We'll do so with a programing exercise.

### Built-in sorting algorithms in Java

Java offers a significant amount of ready to use sorting algorithms. Arrays can be sorted (into their natural order) using the class method `sort` of the `Arrays`-class. Lists can be sorted (into their natural order) using the class method sort of the `Collections` class.

``````int[] numbers = {8, 3, 7, 9, 1, 2, 4};
System.out.println(Arrays.toString(numbers));
Arrays.sort(numbers);
System.out.println(Arrays.toString(numbers));``````
Sample output
[8, 3, 7, 9, 1, 2, 4] [1, 2, 3, 4, 7, 8, 9]
``````ArrayList<Integer> numbers = new ArrayList<>();
System.out.println(numbers);
Collections.sort(numbers);
System.out.println(numbers);``````
Sample output
[8, 3, 7] [3, 7, 8]

Java's built-in sorting algorithms work with value type variables and some of Java's built-in reference type variables, like String. In order for our own classes to be sorted, we need to provide Java with some tips on how to do that, because the classes themselves don't contain information on how objects created from them should be ordered. We'll get back to ordering objects created from classes we made ourselves in the advanced course in programming.

## Information retrieval

Next let's take a look at algorithms meant for information retrieval.

Linear search is a search algorithm that searches for information in an array by going through every value in the array one by one. When the value that was searched for is found, its index is immediately returned. If the requested value cannot be found, linear search returns the information that the value was not found — typically this means returning `-1` instead of a valid index.

``````public class Algorithms {

public static int linearSearch(int[] array, int searched) {
for (int i = 0; i < array.length; i++) {
if (array[i] == searched) {
return i;
}
}

return -1;
}
}``````

In the worst case scenario, i.e when the value searched for isn't found, the algorithm has to do as many comparisons as there are values in the array. In an array containing, say, 10 million values, this means 10 million comparisons. If we are doing more than one search, it makes sense to try and improve efficiency.

### Binary search (aka half-interval search or logarithmic search )

When the data searched is in order, searching can be implemented a lot more efficiently than in linear search. The idea behind Binary Search is to start looking for the searched value in the middle index of the array (or list), compare the value found there to the searched value, and if needed (i.e, when the value isn't found there) eliminate half of the search area. The algorithm is more thoroughly introduced in the following slideshow.
{"ft_lang_label":"__label__en","ft_lang_prob":0.89837706,"math_prob":0.8507874,"size":4114,"snap":"2022-05-2022-21","text_gpt3_token_len":841,"char_repetition_ratio":0.14209245,"word_repetition_ratio":0.034375,"special_character_ratio":0.20952845,"punctuation_ratio":0.13307494,"nsfw_num_words":0,"has_unicode_error":false,"math_prob_llama3":0.95923746,"pos_list":[0],"im_url_duplicate_count":[null],"WARC_HEADER":"{\"WARC-Type\":\"response\",\"WARC-Date\":\"2022-05-25T09:45:42Z\",\"WARC-Record-ID\":\"<urn:uuid:42fe4950-4957-4efa-ae50-4bd6e8f38831>\",\"Content-Length\":\"150390\",\"Content-Type\":\"application/http; msgtype=response\",\"WARC-Warcinfo-ID\":\"<urn:uuid:57969911-f243-437c-a8f3-c976af7bbc0a>\",\"WARC-Concurrent-To\":\"<urn:uuid:a45de90a-63ad-4b85-a7f1-9f9487d47e5d>\",\"WARC-IP-Address\":\"76.76.21.98\",\"WARC-Target-URI\":\"https://java-programming.mooc.fi/part-7/2-algorithms\",\"WARC-Payload-Digest\":\"sha1:COUVAD32KG7USLOSVKBQUVMAU4XC4T2X\",\"WARC-Block-Digest\":\"sha1:3Q7DPA7WZGIKVQ3VO5627RFUBR2SYYWN\",\"WARC-Identified-Payload-Type\":\"text/html\",\"warc_filename\":\"/cc_download/warc_2022/CC-MAIN-2022-21/CC-MAIN-2022-21_segments_1652662584398.89_warc_CC-MAIN-20220525085552-20220525115552-00365.warc.gz\"}"}