Sunday, December 5, 2010

Quick Sort with Bubble Sort



public IList BubbleSort(IList arrayToSort, int left, int right)
{

    for (int i = left; i < right; i++)
    {
        for (int j = right; j > i; j--)
        {
            if (((IComparable)arrayToSort[j - 1]).CompareTo(arrayToSort[j]) > 0)
            {
                object temp = arrayToSort[j - 1];
                arrayToSort[j - 1] = arrayToSort[j];
                RedrawItem(j-1);
                arrayToSort[j] = temp;
                RedrawItem(j);
                pnlSamples.Refresh();
                if (chkCreateAnimation.Checked)
                    SavePicture();
            }
        }
    }

    return arrayToSort;
}

public IList QuickSortWithBubbleSort(IList a, int left, int right)
{
    int i = left;
    int j = right;


    if (right - left <= 6)
    {
        BubbleSort(a, left, right);
        return a;
    }

    double pivotValue = ((left + right) / 2);
    int x = (int)a[int.Parse(pivotValue.ToString())];

    a[(left + right) / 2] = a[right];
    a[right] = x;
    RedrawItem(right);
    pnlSamples.Refresh();
    if (chkCreateAnimation.Checked)
        SavePicture();

    while (i <= j)
    {
        while (((IComparable)a[i]).CompareTo(x) < 0)
        {
            i++;
        }
        while (((IComparable)x).CompareTo(a[j]) < 0)
        {
            j--;
        }

        if (i <= j)
        {
            object temp = a[i];
            a[i++] = a[j];
            RedrawItem(i - 1);
            a[j--] = temp;
            RedrawItem(j + 1);
            pnlSamples.Refresh();
            if (chkCreateAnimation.Checked)
                SavePicture();
        }
    }
    if (left < j)
    {
        QuickSortWithBubbleSort(a, left, j);
    }
    if (i < right)
    {
        QuickSortWithBubbleSort(a, i, right);
    }

    return a;
}

No comments:

Post a Comment