如何添加比较和切换到快速排序和合并排序?

时间:2015-01-20 03:13:03

标签: java quicksort mergesort

我为quicksort和mergesort创建了代码,现在我正在尝试为代码添加比较计数和切换计数,但我无法弄清楚在哪里添加“比较++”和“切换++”。

我的快速排序代码

public void quickSort( int start, int finish )
{
    comparisons = 0;
    switches = 0;
    int[] temp = new int[numbers.length];
    int lowSpot = start;
    int hiSpot = finish;
    int pivot = (int)(Math.random()*(finish+1-start)) + start;
    for( int i = start; i <= finish; i++ )
    {
        if( i != pivot )
        {
            if( numbers[i] <= numbers[pivot] )
            {
                temp[lowSpot] = numbers[i];
                lowSpot++;
            }
            else
            {
                temp[hiSpot] = numbers[i];
                hiSpot--;
            }
        }
    }
    temp[lowSpot] = numbers[pivot];
    for( int j = start; j <= finish; j++ )
    {
        numbers[j] = temp[j];
    }

    if( start < lowSpot - 1 )
    {
        quickSort( start, lowSpot - 1 );
    }
    if( hiSpot + 1 < finish )
    {
        quickSort( hiSpot+1, finish );
    }
    }

我的合并和合并代码

public int[] merge( int[] one, int[] two )
{
    comparisons = 0;
    switches = 0;
    one = mergeSort( one );
    two = mergeSort( two );
    int[] merged = new int[one.length+two.length];
    int oneLoc = 0;
    int twoLoc = 0;
    for( int i = 0; i < merged.length; i++ )
    {
        if( oneLoc < one.length && twoLoc < two.length )
        {
            if( one[oneLoc] <= two[twoLoc] )
            {
                merged[i] = one[oneLoc];
                oneLoc++;
            }
            else
            {
                merged[i] = two[twoLoc];
                twoLoc++;
            }
        }
        else if( oneLoc < one.length )
        {
            merged[i] = one[oneLoc];
            oneLoc++;
        }
        else
        {
            merged[i] = two[twoLoc];
            twoLoc++;
        }
    }
    return merged;
}

public int[] mergeSort( int[] temp )
{
    if( temp.length == 1 )
    {
        return temp;
    }
    else if( temp.length == 2 )
    {
        if( temp[0] > temp[1] )
        {
            int holder = temp[0];
            temp[0] = temp[1];
            temp[1] = holder;
        }
        return temp;
    }
    else
    {
        int mid = temp.length / 2;
        int[] first = new int[mid];
        int[] second = new int[temp.length-mid];
        for( int i = 0; i < temp.length; i++ )
        {
            if( i < mid )
            {
                first[i] = temp[i];
            }
            else
            {
                second[i-mid] = temp[i];
            }
        }
        return merge( first, second );
    }
    }

1 个答案:

答案 0 :(得分:0)

比较是指......比较变量(即start&lt; lowSpot - 1)。切换将在else块中。