简体   繁体   English

Java-整理数组

[英]Java - Sorting out an array

I am encountering some slight and stupid issue while trying to sort out my arrays. 我在尝试整理数组时遇到一些细微而愚蠢的问题。 So here's what I'm doing and what I want to do : 所以这是我在做什么,我想做什么:

I generate an array of ints (good ol' t = new int[];) filled with random generated numbers from -1 to 9. The size of the array is irrelevant. 我生成了一个整数数组(好的ol't = new int [];),其中填充了从-1到9的随机生成的数字。该数组的大小无关紧要。 I would like to make so that each "-1" will get to the end of the array while every other will get "pushed" to take the place. 我想使每个“ -1”到达数组的末尾,而每个其他“ -1”都将推入该位置。

As I'm not a native english speaker it's really hard to express myself correctly on this. 由于我不是英语母语人士,因此很难正确表达自己的意思。

Example : my array is : 9 2 -1 4 6 -1 I want : 9 2 4 6 -1 -1 示例:我的数组是:9 2 -1 4 6 -1我想要:9 2 4 6 -1 -1

I currrently managed to get this BUT it won't work if there are two consecutives -1 cause the second one will get swapped. 我当前设法获得了这个BUT,但是如果有两个连续的-1将无法正常工作,因为第二个将被交换。

Ex : Initial : 9 2 -1 -1 4 6 After modif : 9 2 -1 4 6 -1 例如:初始:9 2 -1 -1 4 6修改后:9 2 -1 4 6 -1

As I said the problem is probably really near from being solved but I really can't find a fix right now. 正如我说的那样,问题可能真的已经解决了,但是我现在真的找不到解决方法。

Here's my code : 这是我的代码:

    for(int i=0;i<NB_CARD;i++)
    {
        t[i]=randomGenerator.nextInt(10)-1;
        System.out.print("t["+i+"]= "+t[i]+"\t\t");
        if(i==4){System.out.println("");}
    }

    //each -1 should be at the end of array
    for(int i=0;i<NB_CARD;i++)
    {
        int tmp=0;

        if(t[i]==-1) 
        {
            for(int y=i;y<NB_CARD-1;y++)
            {
                    tmp=t[y+1];
                    t[y+1]=t[y];
                    t[y]=tmp;
            }
        }
    }

    for(int i=0;i<NB_CARD;i++)
    {
        System.out.print("t["+i+"]= "+t[i]+"\t\t");
        if(i==4){System.out.println("");}
    }

Thank you in advance for every tip/help that could lead me to solve this 在此先感谢您提供的所有提示/帮助,以帮助我解决此问题

A more efficient way of doing this with one loop is. 一种实现此目的的更有效方法是。

int j = 0;
// copy all the non -1 values down.
for (int i = 0; i < NB_CARD; i++)
    if (t[i] != -1)
       t[j++] = t[i];
// fill the rest with -1
Arrays.fill(t, j, NB_CARD, -1);

if NB_CARD == t.length you can do 如果NB_CARD == t.length你可以做

int[] t = {3, -1, -1, -1, 4, 5, 6, -1, -1};
int j = 0;
// copy all the non -1 values down.
for (int i : t)
    if (i != -1)
       t[j++] = i;
// fill the rest with -1
Arrays.fill(t, j, t.length, -1);

System.out.println(Arrays.toString(t));

prints 版画

[3, 4, 5, 6, -1, -1, -1, -1, -1]

In Java 8 you can do this 在Java 8中,您可以执行此操作

int[] t = {6, -1, -1, -1, 4, 5, 3, -1, -1};
List<Integer> sorted = IntStream.of(t).boxed()
        .sorted((a, b) -> (a > -1 ? 1 : 0) - (b > -1 ? 1 : 0))
        .collect(Collectors.toList());
for (int i = 0; i < t.length; i++)
    t[i] = sorted.get(i);
System.out.println(Arrays.toString(t));

which prints 哪个打印

[6, 4, 5, 3, -1, -1, -1, -1, -1]

though it is O(N log N) instead of O(N) and has more code. 尽管它是O(N log N)而不是O(N)并具有更多代码。

我将使用Arrays.sort(T [] a,Comparator c) ,提供您自己的Comparator,它将-1放在输出的末尾。

You can convert the array into list, iterate over list and remove all -1, counting how many you removed. 您可以将数组转换为list,遍历list并删除所有-1(计算删除的数量)。 Then add that many at the end of the list. 然后在列表末尾添加很多。 If the end result has to be an array, you can use List.toArray method to convert it back. 如果最终结果必须是数组,则可以使用List.toArray方法将其转换回。

public static void main(String[] args) {
    Integer[] t = {3, -1, -1, -1, 4, 5, 6, -1, -1};

    List<Integer> list = new ArrayList<>();
    Collections.addAll(list, t);

    int numberOfMinusOnes = 0;
    for (Integer number : list) {
        if (number == -1) {
            numberOfMinusOnes++;
        }
    }

    list.removeAll(Arrays.asList(-1));

    for (int i = 0; i < numberOfMinusOnes; i++) {
        list.add(-1);
    }

    list.toArray(t);

    System.out.println(Arrays.toString(t));
}

Some of boiler plate code can be simplified using google collections library. 某些样板代码可以使用Google收藏库进行简化。 I would also advise to extract some parts into separate methods to increase readability. 我还建议将某些部分提取到单独的方法中以提高可读性。

If I am understanding the code correctly, if you find a -1 , you eventually bubble it up to the end. 如果我正确理解了代码,如果找到-1 ,则最终将其冒泡直至结尾。

What you could do, would be to store the location of the current last element, which at the beginning would be n - 1 . 您可以做的是存储当前最后一个元素的位置,该元素的开头将为n - 1

When you find a -1 , you could replace the i th element with the current last element and then, decrease the value of current by 1. This should allow you to always put any new -1 elements you encounter at the end. 当你发现一个-1 ,你可以代替i当前的最后一个元素个元素,然后,通过减小1的电流值这应该让你始终把任何新的-1你到底遇到元素。

Code wise: 明智的代码:

    int[] t = new int[5];
    t[0] = -1; t[1] = -1; t[2] = 4;

    t[3] = -1;  //Just for demonstration purposes
    t[4] = -1;  //Just for demonstration purposes

    int currentLast = 0;

    for(int i = t.length - 1; i >=0; i--)
    {
        if(t[i] == -1)            
            currentLast = i - 1;
        else
            break;
    }

    for(int i = 0; i < t.length; i++)
        System.out.println(t[i]);

    System.out.println("After");


    for(int i = 0; i < currentLast; i++)
    {
        if(t[i] == -1)
        {   
            int temp = t[currentLast];
            t[currentLast] = t[i];
            t[i] = temp;
            currentLast--;
        }
    }

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

Yields: 产量:

-1
-1
4
-1
-1
After
4
-1
-1
-1
-1

Using bubble sort 使用冒泡排序

package com.appkart.collections;

import java.util.Random;

public class Test {

    public void fillRandomNumber(int a[]) {
        Random random = new Random();
        for (int i = 0; i < a.length; i++) {
            a[i] = random.nextInt(10)-1;
        }
    }

    public void printNumber(int a[]) {
        for (int i = 0 ; i < a.length ;i++) {
            System.out.print(a[i] +" ");
        }
    }

    //Using bubble sort
    public void sortRandomNumber(int a[]) {
        int length = a.length;
        int temp;

        for (int i = 0; i < length; i++) {
            for (int j = 1; j < length - i; j++) {
                if (a[j - 1] < a[j]) {
                    temp = a[j - 1];
                    a[j - 1] = a[j];
                    a[j] = temp;
                }
            }
        }
    }

    public static void main(String[] args) {

        int a[] = new int[10];
        Test test = new Test();
        test.fillRandomNumber(a);
        System.out.println("Random Number bofore sort");
        test.printNumber(a); 
        test.sortRandomNumber(a);
        System.out.println("\n Random Number after sort");
        test.printNumber(a); 
    }
}

You can use something like this: 您可以使用如下形式:

int[] a = { 9, 2, -1, 4, 6, -1 };
for(int i=a.length-1; i>0; i--)
{
    for(int j=0; j<i; j++)
    {
        if(a[i] < a[j])
        {
            int jvalue = a[j];
            a[j] = a[i];
            a[i] = jvalue;
        }
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM