The professional, friendly Java community. 21,500 members and growing!

The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.

Need help merging arraylists and sorting

First time posting here and I'm looking for a little bit of help. Basically what I need to do is develop an algorithm and than code it.

The situation is I need to create two array lists, one 30 numbers and the other 20 (the array lists are full of random numbers), and add them into one array in order from either lowest to highest, or highest to lowest. I can easily figure out what to do with the algorithm, and I know how to add them together, but the trouble I have is adding them in order from low/high or high/low.

I could easily just use the ArrayList add() method and than sort them, but my professor would like it to sort them as each individual number is added. I don't have any code ATM as I'm just looking for some guidance rather than the answer. Not gonna learn with just the answer. Any help is appreciated. I was looking towards using a for loop but not sure in what way.

Re: Need help merging arraylists and sorting

The main part you need is the merge function. It takes 2 lists that are in sorted order (from you're description it looks like you'll need to sort those two lists first, use which ever method you like best), then goes through each list, remove the smaller (or larger, depending on if you're sorting lower-to-higher or higher-to-lower) of the two elements at the front of the lists, then add that element to the front of your new list. Repeat until both lists are empty. If one list is empty, you can "dump" the remaining sorted items in the other list into the end of your new list.

Re: Need help merging arraylists and sorting

The main part you need is the merge function. It takes 2 lists that are in sorted order (from you're description it looks like you'll need to sort those two lists first, use which ever method you like best), then goes through each list, remove the smaller (or larger, depending on if you're sorting lower-to-higher or higher-to-lower) of the two elements at the front of the lists, then add that element to the front of your new list. Repeat until both lists are empty. If one list is empty, you can "dump" the remaining sorted items in the other list into the end of your new list.

A lot of that looks like foreign language to me and I was wondering if their was any way I could do it in just a quick for loop, as I posted shortly after you.