Reputation: 217
In a recent interview I was asked to write sorting algorithm. I did it in following way. I wanted to understand what is wrong in this approach? When I test with 500 intergers it gives better time complexity than bubble sort. Reason I am asking is, that interviewer failed me for this.
static int[] SortedNumbers(int[] numbers)
{
for (int i = 0; i < numbers.Length - 1; i++)
{
int temp;
if (numbers[i] > numbers[i + 1])
{
temp = numbers[i];
numbers[i] = numbers[i + 1];
numbers[i + 1] = temp;
}
if (i > 0)
{
for (int j = 0; j < i; j++)
{
if (numbers[j] > numbers[i])
{
temp = numbers[i];
numbers[i] = numbers[j];
numbers[j] = temp;
}
}
}
}
return numbers;
}
Upvotes: 0
Views: 89
Reputation: 2255
This is effectively a bubble sort. The interviewer might have wanted to hear about some well known, more efficient algorithms like Quicksort. If you are going to an interview, be prepeared with well known algorithms, do no invent your own!
Also when you argue about run time of an algorithm, do not use a specific set of data on which the algorithm operates, but rather talk about run time characteristic. This may be a good entry point to research the subject:
http://en.wikipedia.org/wiki/Big_O_notation
Upvotes: 1