Skip to content

Instantly share code, notes, and snippets.

@Ezeji
Last active April 27, 2021 03:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Ezeji/01cf4d9e7aca04fdc0a39a6a24f1eed3 to your computer and use it in GitHub Desktop.
Save Ezeji/01cf4d9e7aca04fdc0a39a6a24f1eed3 to your computer and use it in GitHub Desktop.
This algorithm focuses on finding the position of a number in a sorted array.
class Program
{
private static List<int> ResultWhenValIsInArray { get; set; } = new List<int>();
private static List<int> ResultWhenValIsNotInArray { get; set; }
static void Main(string[] args)
{
ResultWhenValIsInArray.Add(-1);
ResultWhenValIsInArray.Add(-1);
int[] nums = { 0, 8, -2, 5, 0 };
int val = 0;
var result = NumberPositionInArray(nums, val);
foreach (var item in result)
{
Console.WriteLine("ArrayElement:" + " " + item.ToString());
}
}
public static List<int> NumberPositionInArray(int[] nums, int val)
{
if (nums == null)
{
ResultWhenValIsInArray.Add(0);
}
else
{
Array.Sort(nums);
for (int i = 0; i < nums.Length; i++)
{
if (nums[i] == val)
{
ResultWhenValIsInArray.RemoveRange(0, 1);
ResultWhenValIsInArray.Add(i);
}
else
{
ResultWhenValIsNotInArray = new List<int>(ResultWhenValIsInArray);
}
}
}
if (ResultWhenValIsNotInArray.Count != 0)
{
return ResultWhenValIsNotInArray;
}
else
{
return ResultWhenValIsInArray;
}
}
}
@meekg33k
Copy link

Hello @Ezeji, thanks for participating in Week 3 of #AlgorithmFridays.

Looking through your solution, it doesn't pass all the test cases, especially the test case for an empty array. The requirement was that the code should return [-1. -1] if val isn't found in the array but I'm not sure I see that here.

@Ezeji
Copy link
Author

Ezeji commented Apr 25, 2021

Hi @meekg33k,

I just updated my code to take care of all edge cases as to the problem requirement.

Thanks for pointing out.

@meekg33k
Copy link

Really commendable effort @Ezeji, and thanks for updating your solution. All the test cases pass now.

However, with regards to optimizing your solution, what effect do you think sorting the array has on your solution? Do you think you would have come up with a much better solution without sorting the array?

I have written a blog post here sharing my solution to this problem - a solution that avoids having to sort the array. Please read through and let me know what you think.

Thank you once again for participating once again and see you on Friday for Week 4 of #AlgorithmFridays.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment