Skip to content

Instantly share code, notes, and snippets.

@ivankahl
Created November 19, 2015 20:03
Show Gist options
  • Select an option

  • Save ivankahl/fd2e25ef330ff6034cbe to your computer and use it in GitHub Desktop.

Select an option

Save ivankahl/fd2e25ef330ff6034cbe to your computer and use it in GitHub Desktop.
static int LinearSearchWithFlag(int[] items, int itemToSearch)
{
// Initialize our counter (i) to 0 (the position of the first
// element)
int i = 0;
// Loop through the array until we reach the end or until the
// the item at the current index matches the item we are looking
// for
while (i < items.Length && items[i] != itemToSearch)
i++;
// Check if the while loop ended because it reached the end of
// the array or if it found the object. If it reached the end
// of the array, it means that the element wasn't found and we
// set the value of the counter to negative 1 before returning
// it
if (i == items.Length)
i = -1;
// Return the index of the item we are looking for
return i;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment