|
Introduction
Last week I posted an article on a simple C++ template class, XYDataArray, I used in my system development tool. The main purpose of this template class is to store and sort general data types. I needed to implement the same thing in Java, since the tool I developed has a compatible Java version. I checked the Java SDK documentation before writing my own code, and found that almost everything I needed is already there, like the C++ case.
For example, the java.util.Vector class is the kind of array I want, it can dynamically change its size. There are also various implementations of stable sort algorithms in the java.util.Arrays class. For example, the following line of code will sort a Java Object array in ascending order. Arrays.sort(myArray);
And the sort is guaranteed to be stable (equal elements will not be reordered). The objects in myArray has to be mutually comparable, of course (implementing the Comparable interface). There are other forms of the Arrays.sort method that can be used to sort primitive data types (int, double, etc.) and even subarrays. What about sorting in descending order (note that sorting in ascending order and then reversing the orders of all elements makes it unstable)? In that case, you have to implement a Comparator class and pass an object of this class along with the data array, into another Arrays.sort method. This is like passing a function pointer to a generic sort function in C++. It is not exactly what I wanted. For example, I don't want to implement a different Comparator class for each different way I want to sort my data. What I really need is sorting the indices instead of the data array itself. For example, I want to get the index of the 10th largest element or the index of the 6th smallest element in my array. The SortIndex method in my C++ code will give me exactly what I needed. The best part about the SortIndex method is, I can use it repeatedly to do multi-column sorting on tabulated data (each column is in a separate array) without rearranging the data elements! So I converted my C++ template class, XYDataArray, into a Java class, XYObjArray.
The XYObjArray class is almost identical to its C++ counterpart except that there is no template or operator overloading in Java. In order to use the sort feature, objects in this class have to be mutually comparable (implementing the Comparable interface). I have included source code and a simple test program. There is no restriction on using the source code. The test program creates an array with randomly generated data and then sorts the array (and also verifies that the sort is done correctly). Here is the command line that runs the test program, assuming you already compiled the code and set the correct ClassPath. java ArrayTest
Here are the descriptions of the methods in XYObjArray:
Methods
public XYObjArray( );
This method constructs an empty array.
public XYObjArray(Object[ ] pObj, int nGrowBy);
This method constructs an array with given Object array pObj. The nGrowBy parameter specifies how the array's internal buffer grows or shrinks. The nGrowBy = 64 means that the internal buffer will grow in multiples of 64 elements.
public final synchronized int Find(Object obj);
This method returns the index of obj within the array. The return value is -1 if obj is not found. If the array is already sorted, this method will use binary search instead of linear search.
public final synchronized int Locate(Object obj);
This method returns the position at which to insert a new element obj. If the array is already sorted, inserting at the returned position will keep the array sorted.
public final synchronized void SetSize(int nSize, int nGrowBy);
This method changes the size of the array. If the new size is bigger than the original size, the array will be chopped. Otherwise, null elements will be added if necessary. In any case, the original elements, except the ones being chopped off, will be preserved.
public final synchronized int GetSize( );
This method returns the current size of the array.
public final synchronized Object[ ] GetDataPtr( );
This method returns the internal data buffer.
public final synchronized Object GetAt(int nIndex);
This method returns the element at the position nIndex.
public final synchronized int Add(Object obj);
This method adds a new element obj to the array. If the array is already sorted, adding the new element will keep the array sorted. Otherwise, the new element will be appended to the end of the array. The return value is the position of the newly added element.
public final synchronized int Insert(int nIndex, Object obj);
This method inserts a new element obj to the array at position nIndex. The return value is -1 if nIndex is invalid (out of the range between 0 and the size of the array). Otherwise, it returns nIndex.
public final synchronized int Remove(int nIndex);
This method removes the element at position nIndex from the array. The return value is -1 if nIndex is out of range. Otherwise, it returns the size of the new array.
public final synchronized int SetAt(int nIndex, Object obj);
This method assigns the element obj to position nIndex in the array. The return value is -1 if nIndex is out of range. Otherwise, it returns nIndex.
public final synchronized void Push(Object obj);
This method adds a new element obj to the end of the array.
public final synchronized Object Pop( );
This method removes an element from the end of the array, the return value is the element being removed.
public final synchronized int GetSort( );
This method returns 1 if the array is sorted in ascending order, it returns -1 if sorted in descending order. Otherwise, it returns 0.
public final synchronized void SetSort(int nSort);
If nSort is 1, it will sort the array in ascending order if not already sorted. If nSort is -1, it will sort the array in descending order if not already sorted.
public final synchronized virtual void Sort(int nSort);
This method sorts the array. nSort specifies what order to sort, 1 for ascending, -1 for descending.
public final synchronized virtual void SortIndex(int[ ] arrayIndex, int nSort);
This method does not sort the array itself, instead, it sorts an index array according to the specified order. arrayIndex must be an integer array containing integers 0, 1, 2, ..., nSize-1, where nSize is the size of the current array. The Sort method is implemented using this method. The algorithm is a combination of insertion sort and "randomized" quick sort. The performance is as good as the Arrays.sort method in Java JDK for randomly generated data, according to my tests. The Arrays.sort method performs better when the input data is nearly sorted.
| You must Sign In to use this message board. |
|
| | Msgs 1 to 21 of 21 (Total in Forum: 21) (Refresh) | FirstPrevNext |
|
 |
|
|
i am a IT student,i need help for my case study because its is so difficult!!! My case study is quick Sort!!! plss send in my email!!
|
| Sign In·View Thread·PermaLink | |
|
|
|
 |
|
|
Hello, i'm new and also beginner in java. I tried to make sort in java (JCPro) but i don't know how. Can anyone tell me? The sort run in windows mode not DOS-MODE. There is also 4 option to choose : 1.insertion 2.sequential 3.bubble 4.quick So you can choose what kind of sort you like.you can input the number you want to sort in a textarea and how much the number is.Example : How many number you want to sort : 5 Number 1:5 Numver 2:9 Number 3:4 Number 4:3 Number 5:6
And you can see the sort run in animation. example: there is 5 box with 5 number that you input and the box is moving and change its colour. Please help me with this. Thanks. You can see the example in www.cs.oswego.edu/~mohammad/classes/csc241/samples/sort/Sort2-E.html[^]. But this only works if your IE or Mozilla supported with Java. How can i make it like that but ina simple code? Because all that i have found is already intermediate.
|
| Sign In·View Thread·PermaLink | 2.00/5 (1 vote) |
|
|
|
 |
|
|
I have a vector of vectors:
Vector vecRow = new Vector(); Vector vecCol = new Vector();
vecRow.add(aa); vecRow.add(bb); vecCol.add(VecRow);
this is the structure like a 2D matrix. I need to sort by first colum ??
kakofoniks
|
| Sign In·View Thread·PermaLink | 1.00/5 (1 vote) |
|
|
|
 |
|
|
import java.util.Comparator; import java.util.List; /** * A comparator to sort Lists of data based on a column within each List */ public class ListComparator implements Comparator { private int column; private boolean ascending; ListComparator(int column, boolean ascending) { this.column = column; this.ascending = ascending; } public int compare(Object a, Object b) { List v1 = (List)a; List v2 = (List)b; Object o1 = v1.get(column); Object o2 = v2.get(column); // Treat empty strings like nulls if (o1 instanceof String && ((String)o1).length() == 0) { o1 = null; } if (o2 instanceof String && ((String)o2).length() == 0) { o2 = null; } // Sort nulls so they appear last, regardless of sort order if (o1 == null && o2 == null) return 0; if (o1 == null) return 1; if (o2 == null) return -1; // Compare objects if (o1 instanceof Comparable) { if (ascending) { return ((Comparable)o1).compareTo(o2); } else { return ((Comparable)o2).compareTo(o1); } } else // Compare as a String { if (ascending) { return o1.toString().compareTo(o2.toString()); } else { return o2.toString().compareTo(o1.toString()); } } } }
|
| Sign In·View Thread·PermaLink | 2.00/5 (1 vote) |
|
|
|
 |
|
|
Hi, need help on sorting 2D arrays...
eg. have a String array of 7 full names and want to sort by lastname, how to tackle this in java programming?
i tried to use the for loop on the lastname column but the problem is the firstnames are not follows their lastnames after sorting in this way...
any help is much appreciated.
oh by the way, am jus a beginner in java programming.
regards
|
| Sign In·View Thread·PermaLink | 1.33/5 (3 votes) |
|
|
|
 |
|
|
i need to: 1. read thru a ord document, looking for numbers, and store those numbers in an array 2. do this for numerous documents 3. compare the arrays from each document
|
| Sign In·View Thread·PermaLink | 1.50/5 (2 votes) |
|
|
|
 |
|
|
Anonymous wrote: i need to: 1. read thru a ord document, looking for numbers, and store those numbers in an array 2. do this for numerous documents 3. compare the arrays from each document
Then what are you waiting for? Start working, man.
|
| Sign In·View Thread·PermaLink | |
|
|
|
 |
|
|
 |
|
|
JDBC
Contents problem statement database specification description of java program imputant information submiiting your file
problem statement
writing a java program to connect to an oracle database using JDBC.
database specificaton the following schema describe some tables owned by user oodm in the database on logic:
oodm.staff(snum, name, dob address,city , gender, salary, supervisor, dnum) oodm.dept(dnum, dname, manager, mgrstartdate) oodm.deptlocation(dnum, dcity) oodm.project(pnum, pname, pcity, dnum) oodm.workson(snum, pnum, hours)
descriptions of the columns in each table follow. infomation about foreign keys in the tables is shown below.
table column description oodm.staff snum staff number name staff member's name dob staff member's data of birth address staff member's address city city where staff member lives gender either f(female) OR m(male) salary staff member's salary supervisor snum of staff member's supervisor dnum dnum of staff member's department oodm.dept dnum identifying number for department dname name of department manager snum of department's manager mgrstartdate date when manager was appointed oodm.deptlocation dnum dnum of department dcity city where the department is located oodm.project pnum identifying number for project pname project name pcity city where the project is located dnum dnum of department that controls the project oodm.workson snum snum of staff member pnum pnum of a project that a staff member works on hours hours per week that staff member works on project
note that a department can be located in more than one city, but a project is located in only one city.
table foreign key referenced table oodm.staff supervisor oodm.staff oodm.staff dnum oodm.dept oodm.dept manager oodm.staff oodm.deptlocation dnum oodm.dept oodm.project dnum oodm.dept oodm.workson snum oodm.staff oodm.workson pnum oodm.project
description of java program
write a java program that will do the following: 1.print the following declaration(replacing the name shown in the example with your name, of course).
2. prompt the user for a username and password to log on to the school of CIS'S Oracle database named stud.
3.prompt the user to enter the Pnum of a project.
4.print the name and city of that project.
5.print the name and the number of hours worked per week for every staff member working on that project.
6.calculate and print the total hours worked per week for all staff members working on that project.
your user interface should look something like this (user responses shown in bold face note that you should use your own username and password in place of the example shown):
enter oracle username: cisspr enter oracle password: the84pass enter project number: p005
project name: adelaide festival project city: adelaide
ATZENI, John 8 McBRIDE, David 16 CERI, Rose 16
Total hours 40
End of SQL
Implement a program which can perform the following actions:
Prompt the user for input file name, read the file and determine the number of alphanumeric characters, the number of words, the number of sentences in the file. To determine the number of sentences the number of periods (dots) should be counted (newlines and tabs should be disregarded). Allow the user to press any keys to return back to the main menu.
Prompt the user for the input and output file names, append the contents of on
|
| Sign In·View Thread·PermaLink | |
|
|
|
 |
|
|
Hello I have a question for you: As you know if we pass an object as an argument to a function it will be by reference. But passing simple types like float or double will be 'by value'. Is it possible to simulate the following C++ instruction in Java:
for e.g. void MyFunction( float& a , int& b )
So that the modified values of a and b are returned as process result? Thank you.
|
| Sign In·View Thread·PermaLink | |
|
|
|
 |
|
|
Yes. In Java, you can use array parameter to "simulate" reference parameter. Here is an example. The test program will print "2" as output. Good luck.
/*********** RefTest.java ************/ class RefTest { void test(int[] pInt) { pInt[0] = 2; } public static void main(String[] args) { int pInt[] = new int[1]; pInt[0] = 1; RefTest obj = new RefTest(); obj.test(pInt); System.out.println(pInt[0]); } }
|
| Sign In·View Thread·PermaLink | |
|
|
|
 |
|
|
 |
|
|
 |
|
|
 |
|
|
Hi All,
For those who are interested in P2P, Web Services, distributed network computing, there is an alternative pure Java based Distributed Network Computing platform. The software is downloadable at www.GreenTeaTech.com.
Chris
|
| Sign In·View Thread·PermaLink | 1.00/5 (1 vote) |
|
|
|
 |
|
|
I want to sort an ArrayList or Vector containing Vector of Vectors.
Eg: I have a ARRAYLIST containg ArrayList(ArrayList) objects which needs to be sorted based on the COLUMN that I select from my UI screen.
|
| Sign In·View Thread·PermaLink | |
|
|
|
 |
|
|
 |
|
|
 |
|
|
Here is how I get quartiles in JBuilder:
ArrayList ray = new ArrayList(numofrecs); myprog.Frame1.myrow.first(); rg = 0; while (myprog.Frame1.myrow.inBounds()) { try { adouble = myprog.Frame1.myrow.getDouble(acolumnnum); ray.add(rg,new Double(adouble); rg++; } catch (DataSetException dse) { } myprog.Frame1.myrow.next(); } java.util.List rine = Collections.synchronizedList(ray); Collections.sort(rine); cQ1 = ((Double)rine.get(( irecs) / 4)).doubleValue(); cQ3 = ((Double)rine.get((3 * irecs) / 4)).doubleValue();
|
| Sign In·View Thread·PermaLink | |
|
|
|
 |
|
|
 |
 | ok. |  | Anonymous | 20:13 25 Jul '01 |
|
|
 |
|
|
General News Question Answer Joke Rant Admin
|