Java int[] 数组(从低到高排序)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9791024/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-16 07:41:17  来源:igfitidea点击:

int[] array (sort lowest to highest)

javaarrayssorting

提问by Austin

So I am not sure why this is becoming so hard for me, but I need to sort high to low and low to high.

所以我不确定为什么这对我来说变得如此困难,但我需要从高到低和从低到高进行排序。

For high to low I have:

对于从高到低,我有:

int a, b;
int temp;
int sortTheNumbers = len - 1;

for (a = 0; a < sortTheNumbers; ++a) {
    for (b = 0; b < sortTheNumbers; ++b) {
        if (array[b] < array[b + 1]) {
            temp = array[b];
            array[b] = array[b + 1];
            array[b + 1] = temp;
        }
    }
}

However, I can't for the life of me get it to work in reverse (low to high), I have thought the logic through and it always returns 0's for all the values. Any help appreciated!

但是,我一生都无法让它反向工作(从低到高),我已经仔细考虑了逻辑,并且它始终为所有值返回 0。任何帮助表示赞赏!

The bigger picture is that I have a JTable with 4 columns, each column with entries of numbers, names, or dates. I need to be able to sort those back and forth.

更大的图景是我有一个包含 4 列的 JTable,每列都有数字、名称或日期条目。我需要能够来回排序这些。

Thanks!

谢谢!

采纳答案by Kennet

Unless you think using already available sort functions and autoboxing is cheating:

除非你认为使用已经可用的排序函数和自动装箱是作弊:

Integer[] arr =
    { 12, 67, 1, 34, 9, 78, 6, 31 };
    Arrays.sort(arr, new Comparator<Integer>()
    {
        @Override
        public int compare(Integer x, Integer y)
        {
            return x - y;
        }
    });

    System.out.println("low to high:" + Arrays.toString(arr));

Prints low to high:[1, 6, 9, 12, 31, 34, 67, 78]

印刷 low to high:[1, 6, 9, 12, 31, 34, 67, 78]

if you need high to low change x-yto y-xin the comparator

如果你需要高向低变化x-yy-x比较器

回答by dty

The only thing you need to do to change the sort order is change

更改排序顺序唯一需要做的就是更改

if (array[b] < array[b + 1])

to

if (array[b] > array[b + 1])

Although, as others have noted, it's very inefficient! :-)

尽管正如其他人所指出的那样,它的效率非常低!:-)

回答by matt b

You are never visiting the last element of the array.

您永远不会访问数组的最后一个元素。

Also, you should be aware that bubble sortis pretty inefficent and you could just use Arrays.sort().

此外,您应该意识到冒泡排序效率很低,您可以只使用Arrays.sort().

回答by kasavbere

You need a more efficient sort. like mergesort. try www.geekviewpoint.com and go to sort

你需要一个更有效的排序。像归并排序。尝试 www.geekviewpoint.com 并进行排序

回答by Zulfiqar Ali

  public class sorting {
  public static void main(String arg[])throws Exception{
  int j[]={1,28,3,4,2};   //declaring array with disordered values  

  for(int s=0;s<=j.length-1;s++){
  for(int k=0;k<=j.length-2;k++){
         if(j[k]>j[k+1]){   //comparing array values

    int temp=0;    
    temp=j[k];     //storing value of array in temp variable 

j[k]=j[k+1];    //swaping values
j[k+1]=temp;    //now storing temp value in array


}    //end if block             
}  // end inner loop    
}
//end outer loop

for(int s=0;s<=j.length-1;s++){
System.out.println(j[s]);       //retrieving values of array in ascending order 

}   

}
}

回答by dario nascimento

If you just want sort the int array: Use the quicksort... It's not a lot of code and it's N*lgN in avarage or N^2 in worst-case. To sort multiple data, use the Java Compare (as above) or a stable sorting algorithm

如果您只想对 int 数组进行排序:使用快速排序...代码并不多,平均为 N*lgN 或在最坏情况下为 N^2。要对多个数据进行排序,请使用 Java 比较(如上所述)或稳定的排序算法

static void quicksort(int[] a,int l, int r){
    if(r <= l) return;
    int pivot = partition(a,l,r);

    //Improvement, sort the smallest part first
    if((pivot-l) < (r-pivot)){
        quicksort(a,l,pivot-1);
        quicksort(a,pivot+1,r);
    }else{
        quicksort(a,pivot+1,r);
        quicksort(a,l,pivot-1);
    }
}

static int partition(int[] a,int l,int r){
    int i = l-1;
    int j = r;
    int v = a[r];
    while(true){
        while(less(a[++i],v));  //-> until bigger
        while((less(v,a[--j]) && (j != i)));    //-> until smaller and not end
        if(i >= j){
            break;
        }
        exch(a,i,j);
    }
    exch(a,i,r);
    return i;
}

回答by SergaRUS

You just need to write onestring Arrays.sort(arr)for low to highfor Java 8.

你只需要编写一个字符串Arrays.sort(arr)从低到高为Java 8。

Arrays.sort(arr, Collections.reverseOrder())for high to low

Arrays.sort(arr, Collections.reverseOrder())前高后低

回答by Ankit Adlakha

You can try with bubble sort: Example shown below

您可以尝试使用冒泡排序:示例如下所示

int[] numbers = { 4, 7, 20, 2, 56 };
int temp;

for (int i = 0; i < numbers.length; i++)
{
       for(int j = 0; j < numbers.length; j++)
       {
                if(numbers[i] > numbers[j + 1])
                {
                            temp = numbers [j + 1];
                            numbers [j + 1]= numbers [i];
                            numbers [i] = temp;
                }
        }
}

for (int i = 0; i < numbers.length; i++)
{
         System.out.println(numbers[i].toString());
}

回答by Sarbjit Singh

Let me know if this works:

让我知道这个是否奏效:

public class prog1 {
    public static void main (String args[]){
        int a[] = {1,22,5,16,7,9,12,16,18,30};

        for(int b=0; b<=a.length;b++){
            for(int c=0; c<=a.length-2;c++){
                if(a[c]>a[c+1]){

                    int temp=0;
                    temp=a[c];

                    a[c]=a[c+1];
                    a[c+1]=temp;
                }
            }

        }
        for(int b=0;b<a.length;b++){
            System.out.println(a[b]);
        }
    }
}

回答by albertjan

In java8 you can do something like this:

在 java8 中,您可以执行以下操作:

temp.stream()
    .sorted((e1, e2) -> Integer.compare(e2, e1))
    .forEach(e -> System.out.println(e));