473,386 Members | 1,819 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,386 software developers and data experts.

A method to sort a parallel array(name,mark,age),sort according to name array?

How do i Write a method to sort the parallel arrays according to the ascending order of names, if the two other arrays are numeric and not string like the name array?

Expand|Select|Wrap|Line Numbers
  1.  
  2. public void sortD(String[]name,int[] age, double[] mark) 
  3.     {
  4.         for (int i = 0; i < age.length - 1; i++) 
  5.         {
  6.             for (int j = 0; j < age.length -1-i; j++) 
  7.             {
  8.                 if (age[j] > age[j + 1]) 
  9.                 {
  10.         /*
  11.         *Swap age with lowest age
  12.         */
  13.                 int ageTemp = age[j];
  14.                         age[j] = age[j + 1];
  15.                               age[j + 1] = ageTemp;
  16.  
  17.              /*
  18.                Swap name using the same index of the age
  19.                        */
  20.  
  21.                         String nameTemp = name[j];
  22.                            name[j] = name[j + 1];
  23.                              name[j + 1] = nameTemp;
  24.  
  25.                 double markTemp=mark[j];
  26.                   mark[j]= mark[j + 1];
  27.                    mark[j + 1]=markTemp;                                               
  28.                 }
  29.  
  30.            }
  31.  
Mar 26 '13 #1

✓ answered by chaarmann

You have this line
Expand|Select|Wrap|Line Numbers
  1. if (age[j] > age[j + 1])
This determines the order of the data in your bubble-sort like algorithm.
Just exchange it with
Expand|Select|Wrap|Line Numbers
  1. if (name[j].compareTo(name[j + 1]) > 0)
and it sorts it by name ascending instead.

If you want a high code quality, use object orientation, that means don't use parallel arrays to store the data, instead create a class Person and store your data in a single array of this class (or even better, in a List instead of in array), using Getter/Setters or fields of this class.
Expand|Select|Wrap|Line Numbers
  1. // keep all data together in a single object
  2. class Person {
  3.     public String name;
  4.     public int age;
  5.  
  6.     // this method is for nice printing
  7.     public String toString() {
  8.         return "name: " + name + " age: " + age;
  9.     }
  10. }
  11.  
  12. // declare storage for many object instances
  13. List personList = new ArrayList();
  14.  
  15. // setup demo data
  16. String[] name = {"B-name", "A-name"};
  17. int[] age = {42, 18};
  18.  
  19. // store data
  20. for (int i = 0, length = name.length; i < length; i++) {
  21.     Person p = new Person();
  22.     p.name = name[i];
  23.     p.age = age[i];    
  24.     personList.add(p);
  25. }
  26.  

And second, don't reinvent sorting algrithms but use Collections.sort()
Expand|Select|Wrap|Line Numbers
  1. // sort by name
  2. class NameComparator implements Comparator { 
  3.     public int compare(Object p1, Object p2) {
  4.         return ((Person)p1).name.compareTo(((Person)p2).name); 
  5.     } 
  6. }
  7. Collections.sort(personList, new NameComparator());
  8.  
  9. // print results
  10. System.out.println("sorted person array=" + personList);
  11.  
So if you run these two code snippets, it will print out:
Expand|Select|Wrap|Line Numbers
  1. sorted person array=[name: A-name age: 18, name: B-name age: 42]
  2.  
If you need more fields like "mark", "addresss" etc, put them into your Person class. If you need to sort by them, write a Comparator for each of them, for example MarkComparator, AddressComparator etc., and sort them by using
Expand|Select|Wrap|Line Numbers
  1. Collections.sort(personList, new MarkComparator());
  2. Collections.sort(personList, new AddressComparator());
  3.  
You can even use anonymous inner classes for that, for example you do not declare a AgeComparator, but sort directly this way:
Expand|Select|Wrap|Line Numbers
  1. Collections.sort(personList, new Comparator() { 
  2.     public int compare(Object p1, Object p2) {
  3.         int age1 = ((Person)p1).age;
  4.         int age2 = ((Person)p2).age;
  5.         return (age1 > age2 ? 1 : (age1 == age2 ? 0 : -1)); 
  6.     } 
  7. });
  8.  
You can even improve more, for example by defining a constructor for your class Person that takes as arguments all the data beloging to one person (Age, Name, etc.). Or if you don't read in arrays with the name, age etc. in the first way and then later assign them to a person list in a separate for-loop, but assign the data directly to a person and then put him in the list. And so on.

2 7151
Rabbit
12,516 Expert Mod 8TB
I don't know what you question is. Is the code throwing an error? What is the error message? Is it not working the way you expect? What do you expect? What is it doing instead?
Mar 26 '13 #2
chaarmann
785 Expert 512MB
You have this line
Expand|Select|Wrap|Line Numbers
  1. if (age[j] > age[j + 1])
This determines the order of the data in your bubble-sort like algorithm.
Just exchange it with
Expand|Select|Wrap|Line Numbers
  1. if (name[j].compareTo(name[j + 1]) > 0)
and it sorts it by name ascending instead.

If you want a high code quality, use object orientation, that means don't use parallel arrays to store the data, instead create a class Person and store your data in a single array of this class (or even better, in a List instead of in array), using Getter/Setters or fields of this class.
Expand|Select|Wrap|Line Numbers
  1. // keep all data together in a single object
  2. class Person {
  3.     public String name;
  4.     public int age;
  5.  
  6.     // this method is for nice printing
  7.     public String toString() {
  8.         return "name: " + name + " age: " + age;
  9.     }
  10. }
  11.  
  12. // declare storage for many object instances
  13. List personList = new ArrayList();
  14.  
  15. // setup demo data
  16. String[] name = {"B-name", "A-name"};
  17. int[] age = {42, 18};
  18.  
  19. // store data
  20. for (int i = 0, length = name.length; i < length; i++) {
  21.     Person p = new Person();
  22.     p.name = name[i];
  23.     p.age = age[i];    
  24.     personList.add(p);
  25. }
  26.  

And second, don't reinvent sorting algrithms but use Collections.sort()
Expand|Select|Wrap|Line Numbers
  1. // sort by name
  2. class NameComparator implements Comparator { 
  3.     public int compare(Object p1, Object p2) {
  4.         return ((Person)p1).name.compareTo(((Person)p2).name); 
  5.     } 
  6. }
  7. Collections.sort(personList, new NameComparator());
  8.  
  9. // print results
  10. System.out.println("sorted person array=" + personList);
  11.  
So if you run these two code snippets, it will print out:
Expand|Select|Wrap|Line Numbers
  1. sorted person array=[name: A-name age: 18, name: B-name age: 42]
  2.  
If you need more fields like "mark", "addresss" etc, put them into your Person class. If you need to sort by them, write a Comparator for each of them, for example MarkComparator, AddressComparator etc., and sort them by using
Expand|Select|Wrap|Line Numbers
  1. Collections.sort(personList, new MarkComparator());
  2. Collections.sort(personList, new AddressComparator());
  3.  
You can even use anonymous inner classes for that, for example you do not declare a AgeComparator, but sort directly this way:
Expand|Select|Wrap|Line Numbers
  1. Collections.sort(personList, new Comparator() { 
  2.     public int compare(Object p1, Object p2) {
  3.         int age1 = ((Person)p1).age;
  4.         int age2 = ((Person)p2).age;
  5.         return (age1 > age2 ? 1 : (age1 == age2 ? 0 : -1)); 
  6.     } 
  7. });
  8.  
You can even improve more, for example by defining a constructor for your class Person that takes as arguments all the data beloging to one person (Age, Name, etc.). Or if you don't read in arrays with the name, age etc. in the first way and then later assign them to a person list in a separate for-loop, but assign the data directly to a person and then put him in the list. And so on.
Mar 28 '13 #3

Sign in to post your reply or Sign up for a free account.

Similar topics

6
by: Xiaozhu | last post by:
say, if you had parallel arrays containing the sales person id, the month, and the sales figures (for that person in that month), sorting on sales figure and preserve the order of figures within...
9
by: justanotherguy63 | last post by:
Hi, I am designing an application where to preserve the hierachy and for code substitability, I need to pass an array of derived class object in place of an array of base class object. Since I...
1
by: Jenny | last post by:
Hi, Can I create an array of tags by assigning same name to these tags? For example, I have two <p> tags with the same name t1. But document.all.b.value=document.all.t.length does not...
2
by: Bob Jenkins | last post by:
I have this cute data structure that I just found a second opportunity to use. I googled for references to it, but came up empty. I probably just don't know its name. The algorithm on this...
2
by: nalbayo | last post by:
what's the difference between HttpContext.Current.User.Identity.Name; and Context.User.Identity.Name; thanks!
5
by: David | last post by:
Is there an effecient way to move an array entry up or down in the array? For example. Say you have an array of 5 entries. They are all strings by the way. myArray =...
1
by: Socko | last post by:
I'm trying to fix an sub routine in an VB module that basically reads in a MS database and writes it to an Excel Spread sheet. It works just fine except that the data isn't sorted correctly. I have...
6
by: tc18a | last post by:
I'm looking for a fast algorithm for sorting an array of integers with respect to a master list. For example: Master List: 7 3 9 1 32 6 5 4 99 100 201 13 Array that needs to be sorted array1:...
1
by: sensure | last post by:
why java array starts with zero and why pascal array stars with one?
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.