课程: Java Algorithms
Linear search arrays in Java
- [Instructor] As a software engineer, you'll need to search through data structures using algorithms in order to retrieve relevant data. With a search algorithm, you often need to input the data you need to search and the item you're trying to find. Sometimes the algorithm will return a Boolean, true or false depending on whether the item exists. It can also return the item itself with more data. Let's look at how we can search for data in the array data structure. One option is to do a linear search, also called a sequential search where we look at each item in the array one at a time in order. We can do this using a for each loop. For each integer in the array, if it's equal to the item, we'll return true, we found the item. If we search through the entire array and still cannot find in, then it must not exist in the array and we return false. Another option is to return the data instead of returning true or false. If we find the data, we can return the item. And if we don't find the data, we can return a sentinel value. This is a value we know will never be the value of the item. And it can serve as a not found value. Our sentinel value will be -1. Now our function returns an int. Yet another option instead of returning a sentinel value, we can also return null. However, we need to make the return type integer with a capital I. An int is a primitive data type and cannot be null. Integer is an object so it can have the value null, so that's why it becomes our new return type. Let's try running the function. We get back the data for the first execution and null for the second. This is what we expect. With algorithms, we have many different options for the data we return.
随堂练习,边学边练
下载课堂讲义。学练结合,紧跟进度,轻松巩固知识。