How do I make this program organize the data in it Array
so that the numbers greater than 0 are first and then the zeros in the method Ordenar()
? For example:
Entry
(2,3,0,1,0)
Departure
(2,3,1,0,0)
Here I post the code I have
Scanner leer=new Scanner(System.in);
for(i=0;i<a.length;i++){
System.out.print("ingrese posicion["+i+"]=");
a[i]=leer.nextInt();
}
Ordenar();
}//main
static public void Ordenar(){
//Código que necesito
}
What I understand is that you don't want a traditional "sort", you simply want
0
the numbers to be found last, while the other numbers preserve their order in the array.One method of doing this is in 2 stages:
This method only requires a maximum of
array.length x 2
iterations in the worst case, so it is not very expensive.Code:
Result:
Good morning Camilo, to organize an Array there are different ordering methods already defined, here is an article about it and its implementation in Java. Then, from what I see in your example, you only need to change the position zeros. so I would recommend a modification of the bubble method, which would be like this
Entry
Departure
Here I leave the code already tested, link .
You can initialize the array in which you are going to save the data since in this way you make sure that all the values are going to be 0 by default.
Then you only have to save the last position in which a number greater than zero has come out and save in that position the new value greater than zero that has entered. Once this is done, add one to it so that the next value greater than zero is inserted into the new
ultimaPosicion
.The complete program would be:
This way, you can skip the Sort method and do the sorting directly on the data input.
For entry:
You would have the output:
You should use
public static <T> void sort(T[] a, Comparator<? super T> c)
and create a matcher that does what you want. An implementation would be this:The output is:
According to the situation you pose, the arrangement you need to order it after you have read it. That is, you did not have it previously saved, you only know its length. In this case you can read it conveniently and keep O(n) linear complexity to your function.