在Java中的数组数组织 [英] organizing numbers in an array in Java

查看:101
本文介绍了在Java中的数组数组织的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试着在一个数组举办的随机数从最小到最大的。
我想出了一个循环,我认为应该工作,但有很多的逻辑错误的。

Im trying to organize random numbers in an array from least to greatest. I came up with a loop which I thought should work but has a lot of logic errors.

 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;
  }

谁能告诉我如何解决这一问题或算法自己这样做?

Can anyone tell me how to fix this or an algorithm of their own for doing this?

推荐答案

有几种方法可以进行排序在Java中的数组。在这里,我的文章,但其中3:核心库和2个算法,你可以让你自己的

There are several ways you can sort an array in Java. Here I post but 3 of them : the core library, and 2 algorithms you can make on your own.

1)核心之一:这是字面上code的只有一行。我建议使用这 - 简单,而且非常有效,相比于以下两种溶液

1 ) Core one: This is literally only one line of code. I would suggest using this - simple, and very efficient, compared to the below two solutions.

Arrays.sort(myArray);

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

2 ) Selection Sort : Find the lowest value in an array, move it to the first position, find the next lowest, move to 2nd position, etc.

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)插入排序:插入数组中的每个元素转换成排序的值的成长序列和在阵列的末尾完成。

3 ) Insertion Sort : Inserts each element in the array into a growing sequence of sorted values and finishes at the end of the array.

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中的数组数组织的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆