Reputation: 493
I have a quick sort program using lists.
The error is in the quick sort function return statement.
System.Collections.List does not contain definition for Concat and the best extension method System.Collections.Generic.IEnumerableTsource has some invalid arguments.
The code is as follows.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Enter the n9o. of elements: ");
int n = Convert.ToInt32(Console.ReadLine());
List<int> unsorted = new List<int>();
Console.WriteLine("Enter the elements: ");
for (int i = 0; i < n; i++)
{
unsorted.Add(Convert.ToInt32(Console.ReadLine()));
}
List<int> sorted = quicksort(unsorted);
foreach (int entry in sorted)
{
Console.Write(entry + "\t");
}
return;
} //end of main.
public static List<int> quicksort(List<int> given)
{
if (given.Count == 1)
return given;
int mid = given.Count / 2;
List<int> less = new List<int>();
List<int> big = new List<int>();
for (int a = 0; a < given.Count; a++)
{
if (given[a] < mid)
{
less.Add(given[a]);
}
else
big.Add(given[a]);
}
return (quicksort(less).Concat(given[mid]).Concat(quicksort(big)));
}
}//end of class.
}//end of namespace.
Upvotes: 1
Views: 1471
Reputation: 1928
I think adding given[mid] to the resulting list is a mistake, since it will add the item to your resulting list twice...
also, you need to test against given[mid] not mid
So you should change your if statement to:
if (given[a] < given[mid])
less.Add(given[a]);
else if (given[a] > given[mid])
big.Add(given[a]);
This is assuming that all numbers are unique as well, because if given[mid] is not unique, then you have a problem
Upvotes: 1
Reputation: 56546
You can't Concat
an int
into an IEnumerable<int>
. You could instead wrap it in an array and Concat
that to your other lists:
return quicksort(less)
.Concat(new[] { given[mid] })
.Concat(quicksort(big))
.ToList();
Upvotes: 5
Reputation: 887657
As the error is trying to tell you, the Concat()
method takes a collection of items to concatenate, not a single int
.
Upvotes: 3