【问题标题】:Logic error in the Sorts?排序中的逻辑错误?
【发布时间】:2015-03-31 02:21:18
【问题描述】:

我一直致力于对由字符串组成的数组进行排序,这是我的代码

public static void bubbleSort(String[] values)
{
    boolean swapped = true;
    while (swapped)
        {
            swapped = false;
            for (int count = 0; count<values.length-1;count++)
            {
                if(values[count].compareTo(values[count+1])>0)
                    swap(values,count,count+1);
                swapped = true;
            }
        }
}


public static void selectionSort(String[] values)
{
    int first =0, last = values.length-1,biggest = 0;
    while (last > first)
    {
        biggest = maxIndex(values);
        swap (values, biggest,last);
        last --;
    }
}

private static void swap(String[] values, int first, int second)
{
    String temp = values[first];
    values[first] = values[second];
    values[second] = temp;
}

public static int maxIndex(String[] values)
{
    int index=0;
    for(int count=0; count<values.length; count++)
    {
        if(values[count].compareTo(values[index])>0)
        {
            index=count;
        }
    }
    return index;
}

当我尝试通过测试仪运行气泡排序时,没有打印任何内容,而 selectionSort 仅返回未排序的字符串。

Eclipse中没有语法错误,所以我应该假设算法或代码一定有逻辑错误吗?

【问题讨论】:

    标签: java bubble-sort selection-sort


    【解决方案1】:

    对于冒泡排序

     for (int count = 0; count<values.length-1;count++)
     {
       for(int j=0;j<values.length-1;j++)
       {
            if(values[j].compareTo(values[j+1])>0)
                       swap(values,count,count+1);
        }
      }
    

    以下是一轮冒泡排序如何工作的示例?

    这只是一轮,我们要做 n*n 轮,

    冒泡排序的复杂性:О(n2)

    【讨论】:

      猜你喜欢
      • 2015-12-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多