Search code examples
c#algorithmsearcharray-algorithms

Linear search on array with duplicate values


Okay so I have an algorithm that performs a linear search on an array of doubles. When it finds the element it gives me the location within the array. The problem is that i dont know how to adjust the algorithm so that it accounts for duplicate elements. I would like it to still display the locations of the elements however im struggling to do this... Im also not sure if the step counter is actually working. Would be great if anyone could help thanks!

int i = 0;
double item = 0;
int pos = 0;
int steps = 0;

Console.Write("Enter item to search in array : ");
item = double.Parse(Console.ReadLine());

//Loop to search element in array
for (i = 0; i < LowArr.Length; i++)
steps++

{
    if (item == LowArr[i])
    {
        pos = i + 1;
        break;
    }
}

if (pos == 0)
{
    Console.WriteLine("Item Not found in array");
    Console.WriteLine("Steps taken in Search: " + steps);
}
else
{
    Console.WriteLine("Position of item in array: " + pos);
    Console.WriteLine("Steps taken in Search: " + steps);

If the value is found within the array multiple times i would expect it to tell me the locations.


Solution

  • If the value is found then all you need to do is print the position:

    bool found = false;
    for (i = 0; i < LowArr.Length; i++) {
      if (item == LowArr[i]) {
        Console.WriteLine("Position of item in array: " + i);
        found = true;
      }
    }
    if (!found) {
      Console.WriteLine("Item Not found in array");
    }
    

    I also added a boolean flag so we can add a message if the item wasn't found. If we were only looking for the first occurrence then you could've breaked from the loop when it was found and checked if i == LowArr.length to test if it wasn't found.