Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Sorting an array list into numerical order - help please!!

 
celine scarlett
Ranch Hand
Posts: 93
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

I've written a short class with an int array, which produces a list in the order they were added to the table. The list is taken from a text file with 10,000 numbers.

My problem is that I want to be able to keep the array in numerical order, and currently I have no idea how to achieve this.

My code is currently as follows:



Any help would really be appreciated!!
 
Sunny Kumar
Ranch Hand
Posts: 57
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
To keep your array sorted, you can try Arrays.sort(yourArrayName) method in Arrays.For more info look at this doc
 
celine scarlett
Ranch Hand
Posts: 93
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

Anybody know how I might achieve a sort of an array list without using the 'Arrays' class. For example, possibly modifying the 'add' method in the existing code?

Thanks!
 
Sunny Kumar
Ranch Hand
Posts: 57
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by celine scarlett:
Hi,

Anybody know how I might achieve a sort of an array list without using the 'Arrays' class. For example, possibly modifying the 'add' method in the existing code?

Thanks!


If you want to manaully sort your array then you can try bubble sort coding. However calling it everytime after adding a new element can be a little expensive in terms of performance if your array is quite large or changing frequently.
 
Tom Blough
Ranch Hand
Posts: 263
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If you have to use an array, and you cannot use the Arrays class to sort them, you will have to implement your own sorting algorithm. Do a web search on sorting algorithms. A bubble sort will be the simplest to implement and should work fine for the limited number of items you have.

If you are not limited to arrays, you might check out the SortedSet class in the Java API. You'll have to wrap your int values in Interger objects before adding them to the set.

Cheers,
 
celine scarlett
Ranch Hand
Posts: 93
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

That's great. Thanks for all the help. I shall persevere with this problem tomorrow, and hopefully be able to report some success.

Many thanks.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic