public class Sort
{
// array of integers to hold values
//made it object to support any data type
private object[] array = null;
// number of elements in array
//made it object to support any data type
private object x;
public Sort()
{
//was an int
array = new object[100];
x = array.Length;
Random rand = new Random(5433);
for (int i = 0; i < array.Length; i++)
{
array[i] = rand.Next(-100, 100);
}
PrintArray();
q_sort(0, x - 1);
PrintArray();
}
private void PrintArray()
{
for (int i = 0; i < array.Length - 1; i++)
{
Console.Write(array[i] + ", ");
}
Console.WriteLine(array[array.Length - 1]);
}
public void q_sort(object left, object right)
{
object pivot, l_hold, r_hold;
l_hold = left;
r_hold = right;
pivot = array[Convert.ToInt32(left)];
while (Convert.ToInt32(left) < Convert.ToInt32(right))//This will only take integers?
{
while ((array[right] >= pivot) && (left < right))
{
right--;
}
if (left != right)
{
array[left] = array[right];
left++;
}
while ((array[left] <= pivot) && (left < right))
{
left++;
}
if (left != right)
{
array[right] = array[left];
right--;
}
}
array[left] = pivot;
pivot = left;
left = l_hold;
right = r_hold;
if (left < pivot)
{
q_sort(left, pivot - 1);
}
if (right > pivot)
{
q_sort(pivot + 1, right);
}
}
}
我能够找到的是我需要用对象类型来做这件事。我还是C#的新手,所以我对此有点麻烦。如果我只使它接收整数,双精度等我的代码有效。我只是不确定如何通过排序
进行输入答案 0 :(得分:1)
首先,您应该首先使用如下的泛型类:
public class Sort <T> where T : IComparable<T>
{
private T[] array;
private T object x;
...
public void q_sort(T left, T right)
{
T pivot, l_hold, r_hold;
...
}
}
其次,不要使用>=
<=
>
<
或=
等运算符来比较对象,而是使用obj.CompareTo(otherObj)
其中obj和otherObj类型为T.然后,您将能够根据CompareTo
的返回值确定它们所处的顺序。见
根据http://msdn.microsoft.com/en-us/library/4d7sx9hd%28v=vs.110%29.aspx
的文件小于零: 该对象小于方法参数。
零点: 该对象等于方法参数。大于零: 该对象大于方法参数。