?
Solved

Java - how to sort array

Posted on 2009-12-25
19
Medium Priority
?
520 Views
Last Modified: 2013-12-14
I am trying to write a program that asks the users for name and age, and then sorts them by age.I have found a tutorial here http://onjava.com/onjava/2003/03/12/java_comp.html#listing4 (scroll down and listing5 is the 2nd part of the program). I am trying to expand on this tutorial by asking the user for input, the input is then stored and sorted according to "age".  

Im new to java, but i have attempted to increase the array size by incrementing it, (i created a array [i] and at the end the i is incremented) however when i do a this the lenght does not change at all(i checked in de-bug, the increment does work however the lenght is not altered, is it possible to change the lenght of an array once the program is running? If not is there a way around it?

If not ...

Could someone please show me an example similar to the tutorial above, however for arraylists, how to get user response and sort it. I'm not a total noob, i've been trying for 2 days to do it with no luck =/.. I guess what im asking is how to sort objects within an arraylist

thanks for any help on this matter,any help will be greatly be appreciated (been trying for so long :( )
0
Comment
Question by:rinengan
  • 7
  • 6
  • 3
  • +2
19 Comments
 
LVL 20

Expert Comment

by:a_b
ID: 26123512
Either you change the size of the array here -
Person[] persons = new Person[4];
or use an arraylist data structure.
0
 

Author Comment

by:rinengan
ID: 26123515
that doesnt work because :

if i increase the array size to lets say [10] and attempt to sort it (lets assume i have 3 records pre-set) this will  give a exception error because the compareTO is trying to compare an empty field. I tried to overcome this problem by using a counter but i dont think its possible to extend this ..

regarding the array structure .. could u show me an example? i know how to add objects via scanner and how to pre-set records however i dont know how to use comparable and compare/sort using array lists
0
Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
LVL 23

Expert Comment

by:Ajay-Singh
ID: 26123659
Try using ArrayList, and Collections.sort

ArrayList takes care of dynamic increment of size.
0
 
LVL 8

Expert Comment

by:mnrz
ID: 26124017
check this:
public Person[] sort(Person[] persons) {
    List<Person> personList = Arrays.asList(persons)
    Collections.sort(personList, ,new Comparator<Person>() {
	public int compare(Person p1, Person p2) {
             if(p1.getAge() > p2.getAge()){
               return 1;
             }else if (p1.getAge() < p2.getAge()){
               return -1;
             }  	   
             return 0;
	}
       })
       return personList.toArray();

}

Open in new window

0
 

Author Comment

by:rinengan
ID: 26124153
a_b : but i checked that before, its no good.
ajay : collection.sort works when u have fields of the same nature, in my case i have string and int so i need to create my own comparator, using arrays i can do but it gets confusing when arraylists is involved.

mnrz : Im a bit confused (probably because im new to java so escuse my ignore), is that a comparator for arraylist or arrays?
0
 
LVL 8

Expert Comment

by:mnrz
ID: 26124187
Comparator works with list that is why before sorting I used Arrays.toLisy to convert it to a List
if the option is selected by user (name or age) you need to implements two Comparator so in each case you use appropriate comparator
something like this:
public class NameComparator implements Comparator<Person> {
   //use name to sort
}
and
public class AgeComparator implements Comparator<person> {
//use age to compare
}

public Person[] sort(Person[] persons, Integer option) { 
    List<Person> personList = Arrays.asList(persons) 
    if(option == 1) { // sort by name
     Collections.sort(personList, ,new NameComparator()) ;
       return personList.toArray(); 
    }else if(option == 2) {//sort by age
     Collections.sort(personList, ,new AgeComparator()) ;
       return personList.toArray(); 

}     
 
}

Open in new window

0
 

Author Comment

by:rinengan
ID: 26124218
mnrz do u have msn or yahoo where you might be reached? i still have some questions about that (would be extremely greatful :O)
0
 
LVL 8

Expert Comment

by:mnrz
ID: 26124286
I have no problem with that but if you post your questions here then any person with the same problem can find his/her answer soon.
0
 

Author Comment

by:rinengan
ID: 26124315
im still a bit confused with the first part of the code, cant get it to work . I dont quite understand this part "public Person[] sort(Person[] persons) ". If its an arraylist wouldent [] bring up a syntax error?. Also your code, it only works for only 2 records, no? as it compares age1 with age2, but for example if i have 10 records, how can i compare them all to each other? i dont really want to do age2>age3 age3>age4 .

Would you be kind nuff to paste the whole code that incorporates the sort and age comparision as one? would make things alot clearer. If you dont have the time its ok, im greatful for your help so far. thanks
0
 
LVL 61

Expert Comment

by:Kevin Cross
ID: 26124630
I would have a look again at the code.  The Person[] is the array you original have.  You question is how to sort an "array".  The technique being shown is that you can utilize Collections API and List to accomplish this, so you would pass your array to this method; array is converted to a list; using Collections.sort() with a custom comparator sort the list; return a sorted array.

I am an advocate for using lists versus having to resize arrays, but while I am here note that Arrays.sort() works with an array so you would not necessarily need to recreate this approach as believe it to do the same as shown under the covers.

On the comparison, you have to remember that you are only ever comparing two values as a time so a comparator is always between two objects.  You should not have to alter that code for the number of records ...
0
 
LVL 61

Expert Comment

by:Kevin Cross
ID: 26124640
On the last point, I think all the code you need has been provided.  If this is homework or you are learning ("total noob" in your words), then just getting the code handed to you won't help and for the former is academically dishonest.

You should be going about this the reverse.  Try the code yourself and then post back any issues you have like compilation errors or logical errors where code compiles and runs but the responses you get are not as expected.

Regards,
--isa
0
 
LVL 8

Expert Comment

by:mnrz
ID: 26124642
the public Person[] .... I wrote is a method signature
I presumed you have created a method namely sort(...) which is accepts an array and returns another sorted array.
(Person[] persons) in method signature is an array not a List. inside the method I convert it into a List as you can see in line :
List<Person> personList = Arrays.asList(persons)

And No this code works for any number of element. It is the job of Collections.sort(...) method. The Comparator you implement is only shows how to compare each two objects but it is not important how many element your array has

if you wait I will write a code and attach it later
0
 
LVL 8

Accepted Solution

by:
mnrz earned 2000 total points
ID: 26124780
This code worked fine for me
This is a complete source code with supporting of Ascending and Descending


import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;



public class SortPerson {

	public static void main(String[] args) {
		Person[] persons = new Person[4];
		persons[0] = new Person("Mike", 10);
		persons[1] = new Person("Johny", 8);
		persons[2] = new Person("Jane", 28);
		persons[3] = new Person("Juliet", 15);
		
		SortPerson sp = new SortPerson();
		Person[] sortedByName = sp.sort(persons,1,true);//sort by name ASCending
		Person[] sortedByAge = sp.sort(persons,2,false);//sort by age DESCending;
		System.out.println(sortedByAge);
	}
	
	private Person[] sort(Person[] persons, int type,boolean ascending){
		List<Person> personList = Arrays.asList(persons);
		if(type == 1){
			Collections.sort(personList,new NameComparator(ascending));
			return personList.toArray(new Person[persons.length]);
		}else if (type == 2){
			Collections.sort(personList,new AgeComparator(ascending));
			return personList.toArray(new Person[persons.length]);
		}
		return null;
	}
	
}
class AgeComparator implements Comparator<Person> {
	private boolean asc;
	
	public AgeComparator(boolean ascending) {
		this.asc = ascending;
	}

	public int compare(Person p1, Person p2) {
		if(asc){
			return p1.getAge().compareTo(p2.getAge());
		}else{
			return -1 * p1.getAge().compareTo(p2.getAge());
		}
	}
}
class NameComparator implements Comparator<Person> {
	private boolean asc;
	public NameComparator(boolean ascending) {
		this.asc = ascending;
	}

	public int compare(Person p1, Person p2) {
		if(asc){
			return p1.getName().compareToIgnoreCase(p2.getName());
		}else{
			return -1 * p1.getName().compareToIgnoreCase(p2.getName());
		}
	}
}

class Person {
	private Integer age;
	private String name;
	public Person() {
	}
	public Person(String name,Integer age) {
		this.name = name;
		this.age = age;
	}

	public Integer getAge() {
		return age;
	}
	public void setAge(Integer age) {
		this.age = age;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	
	
}

Open in new window

0
 

Author Comment

by:rinengan
ID: 26124972
Thanks alot mnrz, for having the pacience and time  i really appreciate it.

mwvisa : No its not homework, and i have been trying to do this for a while now and its people like you that are unsuporting that lets this community down. Im not gonna start an argument because im not that kind of person, but i will say thanks to you because when i read your comment i felt somewhat disapointed in myself and i came across the bubble method.

Thanks again mnrz.
0
 
LVL 8

Expert Comment

by:mnrz
ID: 26124981
You're welcome. Could you run that code?
0
 

Author Comment

by:rinengan
ID: 26125011
Yeah, it's perfect, thanks.
0
 
LVL 61

Expert Comment

by:Kevin Cross
ID: 26125970
*laughing* If you look at my two posts above, I answered all your questions for you and then merely pointed out that you were provided code already.  No need for an argument because I am not offended by you feeling me saying you would learn more trying the code already provided to you is letting the community down. :)

Glad you found that mnrz had the right answer.  My only purpose for posting was to support his/her efforts by helping you with the few questions you had on the subject.

Best regards and happy coding,

--isa
0
 
LVL 8

Expert Comment

by:mnrz
ID: 26126483
Yes mwvisa1 I figured out that you were trying to clarify what I post as answer... And I'm sure nobody here is offended. Let's be friend :)
Good luck my friends
0

Featured Post

VIDEO: THE CONCERTO CLOUD FOR HEALTHCARE

Modern healthcare requires a modern cloud. View this brief video to understand how the Concerto Cloud for Healthcare can help your organization.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

For beginner Java programmers or at least those new to the Eclipse IDE, the following tutorial will show some (four) ways in which you can import your Java projects to your Eclipse workbench. Introduction While learning Java can be done with…
In this post we will learn how to make Android Gesture Tutorial and give different functionality whenever a user Touch or Scroll android screen.
Viewers will learn about basic arrays, how to declare them, and how to use them. Introduction and definition: Declare an array and cover the syntax of declaring them: Initialize every index in the created array: Example/Features of a basic arr…
The viewer will learn how to implement Singleton Design Pattern in Java.
Suggested Courses
Course of the Month12 days, 22 hours left to enroll

579 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question