Re: Sorting an array. Fastest way.
Sanny wrote:
I have an array of int.
It is already sorted.
int[] car = new int[100];
Lew wrote:
At this point you have 100 slots for int with no explicit values set, so every
member of the array is set to zero. That is sorted, yes.
Sanny wrote:
Just imagine 100 random numbers are there we sort them.
I have a hard time understanding what you mean by this sentence.
Now we Change the Highest Random number to a new value. Now that new
value need to be ordered at correct place in the sorted array.
For that I use binary search to know position when the new value
should be inserted. But then all other values of arrays has to be
shifted left.
Follow Jeff Higgins advice and resort, or use a Collection that keeps things
in sorted order for you, as Andreas Leitgeib suggested.
This shifting is taking a lot of time. Since every time the First
Value is changed it has to be adjusted in the sorted array.
I wanted to use List. I found util.LinkedList.
There are others, such as ArrayList. Another alternative is the Apache
Commons Collections API.
<http://commons.apache.org/collections/api-release/org/apache/commons/collections/list/TreeList.html>
But I do not understand how to get the value of ith element from a
linmked list. It do not support Int [sic]. So How will I get integer value
from Object.
This was answered in the post you cite below, in the part you cite. I repeat
it in this post as a reminder.
And will not these conversion take more time.
Other posibilities are Vectors and TreeMaps But I dont know what they
are and how to use them.
Read the Javadocs. But don't use Vector.
I have to do ordering 100000s of time So it is taking lot of time is
Sorting the Array.
Since the Array is already Sorted I just want some efficient way to
move an item from First place to ith place and shift other elements.
With an appropriate collection you should delete the desired element, which if
you use java.util.LinkedList takes care of the shift for you,
<http://java.sun.com/javase/6/docs/api/java/util/LinkedList.html#remove(int)>
then add the desired element at the desired location.
<http://java.sun.com/javase/6/docs/api/java/util/LinkedList.html#add(int,%20E)>
This should be faster than manually shifting elements yourself.
Lew wrote:
We need to see a code sample.
It would help to provide an SSCCE:
<http://www.physci.org/codes/sscce.html>
...
Sanny wrote:
But when I use LinkedList car = new LinkedList();
To access ith element I use
int ii=car.get(i); It gives error saying says Object cannot be copied
to int. How to know the value of ith element in LinkedList.
Lew wrote:
LinkedList, like all Lists, holds objects not primitives. You would need to use
Object ii = car.get( i );
Even better would be to use generics. If you used
List <Integer> car = new LinkedList <Integer> ();
then autounboxing (which is occasionally dangerous) would let you get away
with the assignment directly to an int:
int ii = car.get( i );
--
Lew