A Coder’s Corner

Blog de tecnologia y programación

Archive for July, 2008

Custom Sorting for ListBox in C#

Posted by gfaraj on July 31, 2008

Applying a custom sort to a Windows Forms ListBox is not a trivial task. One would think setting the Sorted property to true and implementing the IComparable interface in the item class would be enough. Well, it’s not that simple. Custom sorting a ListBox requires a new implementation of the whole sorting algorithm, by deriving ListBox and overriding the protected Sort method. The following code illustrates how you would override Sort and implement a quicksort algorithm that sorts the items according to their IComparable implementation. Don’t forget that Sort is only called when the Sorted property goes from false to true.

protected override void Sort()
{
    QuickSort(0, Items.Count - 1);
}

private void QuickSort(int left, int right)
{
    if (right > left)
    {
        int pivotIndex = left;
        int pivotNewIndex = QuickSortPartition(left, right, pivotIndex);

        QuickSort(left, pivotNewIndex - 1);
        QuickSort(pivotNewIndex + 1, right);
    }
}

private int QuickSortPartition(int left, int right, int pivot)
{
    var pivotValue = (IComparable)Items[pivot];
    Swap(pivot, right);

    int storeIndex = left;
    for (int i = left; i < right; ++i)
    {
        if (pivotValue.CompareTo(Items[i]) >= 0)
        {
            Swap(i, storeIndex);
            ++storeIndex;
        }
    }

    Swap(storeIndex, right);
    return storeIndex;
}

private void Swap(int left, int right)
{
    var temp = Items[left];
    Items[left] = Items[right];
    Items[right] = temp;
}

Posted in C Sharp, Programación | Tagged: , , , , , , | 2 Comments »