473,395 Members | 1,495 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,395 software developers and data experts.

quicksort for simple phonebook program

Hi,

I'm doing a fairly basic Java course, and I have to design a very simple phone book programme which will take a small number of phone entries (the number can be predefined so I can use arrays instead of lists), sort them and allow them to be searched.

I'm just concentrating on the sorting part of the problem at the moment, and I'm not sure where to start! There's two ways I can approach it:

1) Create an array of objects, each object containing a variable for a Name and a Phone Number, and then use quicksort on the array to sort the objects. The problems with this (for me anyway, I'm sure this is really easy for you guys!) is that I'm not sure on (a) how to get the individual objects into the array in the first place and (b) how to use quicksort in this case so that the Name variable is used for sorting purposes.

2) Create a much simpler string array containing the names as Strings, and have a second array with the relevant Phone numbers in the corresponding index position. The problems with this approach is that while performing quicksort on the String array to move the names around, I don't know how to ensure that the corresponding telephone number in the second array also moves.

Any help or suggestions much appreciated!

Shane
Mar 22 '08 #1
12 5239
JosAH
11,448 Expert 8TB
The Object Oriented way in Java is to implement the Comparable interface
in your PhoneEntry class; the String class also implements this interface, that's
why it is so easy to sort Strings.

If you absolutely don't want to do that, have a look at the Comparator interface,
it can compare two instantiations of a class and decide which one is larger etc.
Read the API documentation for those two interfaces.

Never, ever consider your alternative 2) it is considered a criminal offence to rip
objects apart and stick their remnants in separate arrays. Java is not Fortran
and such practice will be frowned upon.

There's also a 'generic heap sort' article in Java's Howtos section that may be
worth reading.

kind regards,

Jos
Mar 22 '08 #2
sukatoa
539 512MB
Hi,

I'm doing a fairly basic Java course, and I have to design a very simple phone book programme which will take a small number of phone entries (the number can be predefined so I can use arrays instead of lists), sort them and allow them to be searched.

I'm just concentrating on the sorting part of the problem at the moment, and I'm not sure where to start! There's two ways I can approach it:

1) Create an array of objects, each object containing a variable for a Name and a Phone Number, and then use quicksort on the array to sort the objects. The problems with this (for me anyway, I'm sure this is really easy for you guys!) is that I'm not sure on (a) how to get the individual objects into the array in the first place and (b) how to use quicksort in this case so that the Name variable is used for sorting purposes.

2) Create a much simpler string array containing the names as Strings, and have a second array with the relevant Phone numbers in the corresponding index position. The problems with this approach is that while performing quicksort on the String array to move the names around, I don't know how to ensure that the corresponding telephone number in the second array also moves.

Any help or suggestions much appreciated!

Shane
If you like it to have an experiment.

You could use #2 implementation... to avoid more confusions later....

As you add a name, you must also add the number in the same element...

x = 0;
myname = StringName[ x ];
mynumber = StringNumber[ x ];

When you search them, just use the element... 1 element represents 2 values... from arrays....

Since you are using quicksort, you should use 2 temp variables for storing name and number... for swapping values....

Jo's reply is good to implement.

sukatoa...
Mar 22 '08 #3
Laharl
849 Expert 512MB
#2 could be accomplished with a Map. A TreeMap would even store the Strings in (effectively) sorted order...Admittedly, this is more complicated than you probably want to deal with...
Mar 22 '08 #4
JosAH
11,448 Expert 8TB
#2 could be accomplished with a Map. A TreeMap would even store the Strings in (effectively) sorted order...Admittedly, this is more complicated than you probably want to deal with...
Sure, and what to do with two different people having the same name? That option
2) stinks no matter what trickery is applied.

kind regards,

Jos
Mar 22 '08 #5
chaarmann
785 Expert 512MB
Sure, and what to do with two different people having the same name? That option
2) stinks no matter what trickery is applied.
Jos
yes, it's bad practise. Don't separate data that should be together.Solution one is better than 2. But there is a third solution: easier than solution 1 (for a beginner), and in principle like solution 2:

create an array of Strings where each string represents one record. Separate the data inside a string with "|". You can use also another character for separation, but it must be smaller than "a" (= your lexicographically smallest character in the name), or the comparison will fail.
Example:

Expand|Select|Wrap|Line Numbers
  1. String[] array = {
  2.   "police|119", 
  3.   "name2|phone2",
  4.    ...
  5. }
  6.  
  7. // Now sort array. This works, because String class already implements Comparable interface
  8. Arrays.sort(array);
  9.  
  10. // print out array:
  11. System.out.println(Arrays.asList(array));
Mar 22 '08 #6
JosAH
11,448 Expert 8TB
yes, it's bad practise. Don't separate data that should be together.Solution one is better than 2. But there is a third solution: easier than solution 1 (for a beginner), and in principle like solution 2:

create an array of Strings where each string represents one record. Separate the data inside a string with "|". You can use also another character for separation, but it must be smaller than "a" (= your lexicographically smallest character in the name), or the comparison will fail.
Example:

Expand|Select|Wrap|Line Numbers
  1. String[] array = {
  2.   "police|119", 
  3.   "name2|phone2",
  4.    ...
  5. }
  6.  
  7. // Now sort array. This works, because String class already implements Comparable interface
  8. Arrays.sort(array);
  9.  
  10. // print out array:
  11. System.out.println(Arrays.asList(array));
That is just plain hacking; you have sorted a string representation of the original
objects but haven't sorted the objects themselves. That sort of hacking has brought
more misery than good in the past and it gives the IT branch a bad name. It is
worth nothing to do such things and beginners certainly shouldn't resort to that
trickery-dickery.

kind regards,

Jos
Mar 22 '08 #7
Thanks for the answers guys. So I think I'm going to go with the comparable method on option 1 so.

I've started my coding - and I'm having problems getting the my PhoneEntry objects into the array.

I've got a PhoneEntry class which looks like this so far:

Expand|Select|Wrap|Line Numbers
  1. class PhoneEntry 
  2. {
  3.  
  4. //declare class variables
  5. private static String person;
  6. private static int phone;
  7.  
  8. //constructor
  9. public PhoneEntry(String name, int number)
  10.     {
  11.     person = name;
  12.     phone = number;
  13.     }// end constructor
  14.  
  15. public static void print()
  16.     {
  17.     System.out.println("~ " + person + "  ~ " + phone);
  18.     }//end print
  19.  
  20.  
  21. }//end class
  22.  
And I've got a main PhoneBook class in which I am trying to set up an array of 10 objects, and pre-define the data for each of the 10 entries. I'm then just trying to call the print method from the PhoneEntry class to confirm that each object is stored correctly and will print.

Expand|Select|Wrap|Line Numbers
  1. import java.util.*;
  2. class PhoneBook 
  3. {
  4.     public static void main(String[] args) 
  5.     {
  6.         PhoneEntry[] book = new PhoneEntry[10]; //set up the array of PhoneEntry objects
  7.  
  8.         //hard-code 10 phone book entries
  9.         book[0] = new PhoneEntry("Madsen Declan", 016271624);
  10.         book[1] = new PhoneEntry("Madsen Eoin", 016275236);
  11.         book[2] = new PhoneEntry("Courtney Shane", 016275364);
  12.         book[3] = new PhoneEntry("Moran Tess", 016245327);
  13.         book[4] = new PhoneEntry("Leydon Claire", 016271446);
  14.         book[5] = new PhoneEntry("Crean Ruth", 016243354);
  15.         book[6] = new PhoneEntry("Byrne Paul", 016243247);
  16.         book[7] = new PhoneEntry("Hanafin Ruari", 016233214);
  17.         book[8] = new PhoneEntry("Molloy John", 016274342);
  18.         book[9] = new PhoneEntry("Farrell Peter", 016273636);
  19.  
  20.         for (int i = 0; i < book.length; i++)
  21.             PhoneEntry.print();
  22.  
  23.     }//end main
  24. }//end class
  25.  
Both classes are compiling ok, but all I get printed is:

"~ Farrell Peter ~ 3766174" ten times.

Its clear that there's something wrong with the way I'm using my print method to try to print each individual entry, as it's just printing the last name 10 times. And I'm really puzzled by the number that its printing out beside the name, because as you can see from the data I'm using, none of the phone numbers matches this number so I don't know where it came from!
Mar 22 '08 #8
JosAH
11,448 Expert 8TB
How does the static method PhoneEntry.print() know what entry to print? It doesn't
take any parameters so I wonder if there's magic around here ...

kind regards,

Jos
Mar 22 '08 #9
Hmm, yes, I see what you're saying. I've tried a couple of parameters but I don't really know what I'm doing with that, so alternatively I tried to scrap the print method in PhoneEntry and instead changed the private variables in PhoneEntry to public, and created two variables in the PhoneBook class called
Expand|Select|Wrap|Line Numbers
  1. String name = PhoneEntry.person;
  2. int number = PhoneEntry.phone;
  3.  
...thinking that I'd be able to use these to get at the different name and number values, and print directly from the PhoneBook class instead of trying to call a print method from PhoneEntry:

Expand|Select|Wrap|Line Numbers
  1. for (int i = 0; i < book.length; i++)
  2.     System.out.println("~ " + name + "  ~ " + number);
  3.  
....didn't work though. Just got "~ null ~ 0" printed 10 times. *sigh*
Mar 22 '08 #10
chaarmann
785 Expert 512MB
You should read about static methods/variables (class-level) and nonstatic methods/variables (object-level). There is just one memory location for the "person" that is shared among all your instantiated objects, because you declared it "static". You are creating objects here, but you always overwrite your person and number of the previous old object. So when you call your print-method at the end, it just writes the data that you have given as parameters for your last created object.

If you wonder why it prints 3766174?
Because it's the same as the number 01624532, but it is not given in octal as you did (by accident), but decimal!
remember : the leading "0" in front of your number marks an octal system, while a leading "0x" in front of your number marks a hexadecimal system.
therefore 08 does not exist, you would get a compiler error!
For example 10 (decmal) = 012 (=1*8 + 2) (octal) = 0xA (hexadecmal)

if you want leading zeros, just give the number as a String. Or better: give the number without a zero in front, but use functions of class DecimalFormat to print it with leading zero at the end.


Both classes are compiling ok, but all I get printed is:

"~ Farrell Peter ~ 3766174" ten times.

Its clear that there's something wrong with the way I'm using my print method to try to print each individual entry, as it's just printing the last name 10 times. And I'm really puzzled by the number that its printing out beside the name, because as you can see from the data I'm using, none of the phone numbers matches this number so I don't know where it came from!
Mar 22 '08 #11
chaarmann
785 Expert 512MB
That is just plain hacking; you have sorted a string representation of the original
objects but haven't sorted the objects themselves. That sort of hacking has brought
more misery than good in the past and it gives the IT branch a bad name. It is
worth nothing to do such things and beginners certainly shouldn't resort to that
trickery-dickery.

kind regards,

Jos
Plain hacking, quick and dirty, is exactly what I wanted to provide. because it's easier to understand for beginners than dealing with Objects and Comparable interface. If he is a professional, of course I would never suggested that. I just wanted him to concentrate on his task, the "binary sort" algorithm. That's already difficult enough. Once he has mastered that, he can climb up the ladder from "procedural" to "object orientated" programming.
I have forseen that his teacher will tell him to use objects anyhow if he presents the "quick and dirty" solution. But then he will have a nice discussion and learn why this is better.
I mean he was considering solution 2 with the 2 separated string arrays, and you told him this is not good, but he really did not understand WHY it is not good. He can only get the experience from trying it the dirty way and then getting into big trouble when he adds more and more features to his program. (for example if the teacher says, now change your program so that it also can sort by phone number instead by only name). Then he can clearly understand why using the comparable-interface with objects is the best solution.
Mar 22 '08 #12
JosAH
11,448 Expert 8TB
Ok, it's your way then; I leave the poster up to you; the poster is all yours.
I only hop in now and then mumbling about generics and interfaces ;-)

kind regards,

Jos
Mar 22 '08 #13

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

Similar topics

6
by: Scott Niu | last post by:
Hi, I have this following simple c++ program, it will produce memory leak ( see what I did below ). My observation also showed that: There will be a mem leak when all the 3 conditions are true:...
4
by: Raquel | last post by:
A very simple piece of SQLJ: try { #sql sqlj4_iterator = {SELECT PHONENO FROM DB2ADM.EMPLOYEE WHERE WORKDEPT = 'D11'}; while(sqlj4_iterator.next()) {...
8
by: SK | last post by:
Hi I am trying to write a simple C program with devc++ as the complier using the concept of arrays. I cannot get the program to compile without mutiple errors. If anyone has the time to help me...
9
by: Arnaud Miege | last post by:
Hi, I am going through a C tutorial and would like to compile a simple C program using Microsoft Visual Studio .NET 2003. I can open my *.c file but I can't figure out a way to compile it. If...
13
by: asif929 | last post by:
I have been trying to create this chess program from many hours and still couldn't figure out how to complete it. After consume all these efforts i come to this google groups for the first time for...
0
by: Sreekanth | last post by:
I have a simple c program built using VS.Net 2008. I wanted to run this on another program. When I try to run it, I see the following error message. "The system cannot execute the specified...
3
by: Jason | last post by:
I want to create a simple FTP program or service that would: 1.) FTP files in a specific directory to a remote ftp host. 2.) Send off a report telling me if all files transferred or if they...
1
by: jerry | last post by:
i have written a simple phonebook program,i'll show you some of the codes,the program's head file is member.h . i suppose the head file works well.so i don't post it. here's the clips of main...
6
by: pythoNewbie | last post by:
Dear experts, I am trying to understand a simple semaphore program written in C, and trying to insert some printf statements in the code , but there is no output at all. #include<stdio.h>...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
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...
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
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
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...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...

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.