【问题标题】:organizing numbers in an array in Java [duplicate]在Java中组织数组中的数字[重复]
【发布时间】:2013-12-20 10:07:53
【问题描述】:

我试图在一个数组中从最小到最大组织随机数。 我想出了一个我认为应该可以工作但有很多逻辑错误的循环。

 for(int z=0; z<=999;z++){
    for(w=1; w<=999;w++){
      if(z<w){
        if(numberArray[z]<numberArray[w])
         temp=numberArray[w];
        }
    }
    numberArray[z]=temp;
  }

谁能告诉我如何解决这个问题或他们自己的算法来做到这一点?

【问题讨论】:

  • 这叫排序——google插入排序、选择排序、快速排序、归并排序。后两个更高级,前两个更容易实现
  • 使用选择排序会很容易开发
  • 我会使用选择排序来处理这样的事情。
  • 或者更好的是谷歌“java 排序数组”并找到大约 80 亿个库和包,包括核心 java api。

标签: java arrays int organization


【解决方案1】:

Arrays.sort() 是一种快速简便的方法。

如果您需要更强大的功能,还可以考虑 PriorityQueues

This link 是关于 SO 的另一个问题,答案很好。

【讨论】:

  • 你为什么要从一个数组转到PriorityQueue?这似乎有点……没必要。
【解决方案2】:

有几种方法可以在 Java 中对数组进行排序。在这里我只发布了其中的 3 个:核心库和 2 个您可以自己制作的算法。

1 ) 核心一:这实际上只是一行代码。与以下两种解决方案相比,我建议使用它 - 简单且非常有效。

Arrays.sort(myArray);

2 ) 选择排序:查找数组中的最小值,将其移至第一个位置,找到下一个最小值,移至第二个位置,等等。

public void selectionSort(Comparable[] a)
{
    for(int index = 0; index < a.length; index++)
    {
        // find the smallest one in the array from index : end
        int smallest = indexOfMin(a, index);
        // swap the value at index and the value at the smallest one found
        Comparable temp = a[smallest];
        a[smallest] = a[index];
        display.update();
        a[index] = temp;
    }
}

3 ) 插入排序:将数组中的每个元素插入到不断增长的排序值序列中,并在数组末尾完成。

public void insertionSort(Comparable[] a)
{
    for(int i = 1; i < a.length; i++)
    {
        insert(a, i);
    }
}

public void insert(Comparable[] a, int nextIndex)
{
    int index = 0;
    Comparable finalObject = a[nextIndex];
    // Let us first find the first occurence of a comparable greater than our comparable
    while(finalObject.compareTo(a[index]) > 0)
        index++;
    for(int i = (nextIndex-1); i >= index; i--)
        a[i+1] = a[i];
    a[index] = finalObject;
}

【讨论】:

  • 说到排序,Java SE 7 中使用 Timsort O(N) best O(NlogN) 最差的排序(第一个解决方案)
【解决方案3】:

一个班轮:

Arrays.sort(numberArray);

或从大到小顺序:

Arrays.sort(numberArray, Collections.reverseOrder());

或者更好的是,使用保持其内容排序的二叉搜索树,这对于非常动态的集合非常有用,因为添加操作在内存和时间方面比完整的就地排序更便宜:

TreeSet<int> set = new TreeSet<int>();
set.add(10);
set.add(4);
set.add(11);

set.toString();
// prints 4, 10, 11

【讨论】:

    猜你喜欢
    • 2019-05-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-09-28
    • 1970-01-01
    • 2014-11-01
    • 1970-01-01
    • 2011-09-24
    相关资源
    最近更新 更多