Warning: strpos(): needle is not a string or an integer in /home/thebestp/public_html/buildingblocksjava/wp-content/plugins/textlinkads/textlinkads.php on line 175

Warning: strpos(): needle is not a string or an integer in /home/thebestp/public_html/buildingblocksjava/wp-content/plugins/textlinkads/textlinkads.php on line 175

Warning: strpos(): needle is not a string or an integer in /home/thebestp/public_html/buildingblocksjava/wp-content/plugins/textlinkads/textlinkads.php on line 175
Searching | Building Blocks Java

Searching

One common task is searching an array for a specified value. Sometimes the value may be known in advance. Other times you may want to know the largest or smallest element.

Unless you have some special knowledge of the contents of the array (for instance, that it is sorted) the quickest algorithm for searching an array is straight-forward linear search. Use a for loop to look at every element of the array until you find the element you want. Here’s a simple method that prints the largest and smallest elements of an array:

   static void printLargestAndSmallestElements (int[] n) {

    int max = n[0];
    int min = n[0];

    for (int i=1; i < n.length; i++) {
      if (max < n[i]) {
        max = n[i];
      }
      if (min > n[i]) {
        min = n[i];
      }
    }

    System.out.println("Maximum: " + max);
    System.out.println("Minimum: " + min);

    return;

  }
  

If you’re going to search an array many times, you may want to sort the array, before searching it. We’ll discuss sorting algorithms in the next section.

Comments are closed.