NetBeans Java Tutorial – Linear Search #3

In this tutorial I show how to implement a linear search algorithm in Java.

 

 

Code:

package tutorials;
 
import java.util.ArrayList;
 
/**
 *
 * @author Edward
 */
public class Searches {
	public static void main(String[] args) {
		Searches searches = new Searches();
		searches.testLinearSearch();
	}
 
	public void testLinearSearch() {
		ArrayList<String> myArray = new ArrayList<>();
		myArray.add("lemon");
		myArray.add("lime");
		myArray.add("pear");
		myArray.add("apple");
 
		System.out.println(linearSearch(myArray, "orange"));
	}
 
	private int linearSearch(ArrayList<String> array, String toFind) {
		int i = 0;
		for (String val : array) {
			if (val.equals(toFind)) {
				return i;
			}
			i++;
		}
		return -1;
	}
}

Leave a Reply

Your email address will not be published. Required fields are marked *

Name *

This site uses Akismet to reduce spam. Learn how your comment data is processed.