This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 11 years ago.
I am having trouble with sorting my linked list can anyone help me and let me know what I am doing wrong?
I need to sort in and put it in a list.
and If you can give me some pointers to print the list at the end with a new method public void print().
public class SortedLinkedList<T extends Comparable<? super T>>
extends LinkedList<T>
{
private LinkedList<T> list; //the sorted list
//the constructor
public SortedLinkedList(LinkedList<T> in)
{
if(in.isEmpty())
{
System.out.println("Empty list");
}
else
{
LinkedList<T> first = new LinkedList<T>(in.subList(0, in.size()/2));
LinkedList<T> second = new LinkedList<T>(in.subList(in.size ()/2,in.size()));
LinkedList<T> sortList = new LinkedList<T>();
int i = 0;
int j = 0;
while(i<first.size() && j<second.size())
{
if(first.get(i).equals(second.get(j)) || first.get(i).compareTo(second.get(j))<0)
{
sortList.add(first.get(i));
i++;
}
else
{
sortList.add(second.get(j));
j++;
}
if(i == first.size())
{
for(int k = j; k<second.size(); k++)
{
sortList.add(second.get(k));
}
}
else
{
for(int x = i; x<first.size(); x++)
{
sortList.add(first.get(x));
}
}
}
}
}
}
Before writing your own sort try Collections.sort. If you need your own sort order, use a Comparator.
Some addition: In most cases, LinkedLists are the wrong data structure - especially if there's the need for sorting it.
It seems you are trying to implement Mergesort. If my assumption is correct, you are forgetting to call mergesort on the sublists.recursively. The rough algorithm, in pseudo code, would be:
mergesort(list)
left = list[:len(list/2)]
right = list[len(list/2):]
mergesort(left)
mergesort(right)
merge(left, right) # that would be your while loop
Edit: Unless you really need to implement your own algorithm, I suggest using Collections.sort, from the Java API.
Related
I'm creating a program in java to store top 10 highest scores. So, i'm using Array in it. I have question in my mind whether what is to be used singly linked list or array in the program to avoid complexity of the code and make program more efficient.
private int numEntries = 0;
private GameEntry[] board;
public Scoreboard(int capacity){
board = new GameEntry[capacity];
}
public void add(GameEntry e){
int newScore = e.getScore();
if(numEntries<board.length||newScore>board[numEntries-1].getScore()){
if(numEntries<board.length){
numEntries++;
}
int j=numEntries-1;
while(j>0&&board[j-1].getScore()<newScore){
board[j]=board[j-1];
j--;
}
board[j]=e;
}
}
In such cases no need to think too much about performance (unless it is huge numbers), you should write as clear as possible, understandable code. Later you may tune it, but first make sure it logically correct and you really need performance improvement.
Also you don't need to implement sorting, use existing utilities.
I would do it like this:
List<GameEntry> arr = new ArrayList<>();
Comparator<GameEntry> cmp = Comparator.comparingInt(a -> a.getScore());
public void add(GameEntry e) {
arr.add(e);
Collections.sort(arr, cmp.reversed());
while(arr.size() > capacity) {
arr.remove(arr.size()-1);
}
}
This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 10 years ago.
I have this problem with my code. Its called java.lang.nullpointerexception. and I cant seem to fix it. please help me take a look at it. Thank you. I didnt include the class name and import. class name is called CHORD. I didnt make public static since my assginemnt say dont use global variable.
private ArrayList<Integer> nodeList;
public static void main(String[] args){
CHORD obj = new CHORD();
obj.nodeList = new ArrayList<Integer>();
String filename ="";
if(args.length ==1){
filename = args[0];
obj.read(filename);
}
}
public void read(String file){
CHORD obj = new CHORD();
obj = null;
Scanner loadFile = null;
try{
loadFile = new Scanner(new File(file));
String inputLine;
while(loadFile.hasNextLine()){
inputLine = loadFile.nextLine();
String[] inputArray = inputLine.split(" ",3);
if(inputArray[0].equalsIgnoreCase("init")){
int size = Integer.parseInt(inputArray[1]);
setSizeFT(init(size));
}
else if(inputArray[0].equalsIgnoreCase("addpeer")){
System.out.println("adding");
nodeList.add(Integer.parseInt(inputArray[1]));
}
}
}
catch(FileNotFoundException x){
}
finally{
System.out.println(getFT());
loadFile.close();
}
System.out.println(getFT());
}
public void print(){
CHORD obj = new CHORD();
for(int x =0; x< obj.nodeList.size(); x++){
System.out.println(obj.nodeList.get(x));
}
}
public int init(int num){
int n = 23;
double k = Math.ceil(Math.log(n)/Math.log(2));
int size = (int)k;
return size;
}
public void setSizeFT(int size){
sizeFT = size;
}
public int getFT(){
return sizeFT;
}
}
Here's an explanation of what NullPointerException's are: http://antwerkz.com/dealing-with-nullpointerexceptions/ From the article:
The most common (and obvious to the seasoned developer) is that you didn't initialize a variable.
Looking at that line, it looks like obj.nodeList may be null. Here's how I deduced that:
I can see that obj is not null, because the first line is CHORD obj = new CHORD();. That means you didn't set obj to null.
I can tell that Integer is not null. That's a class and you're calling a static method. That can't be null because there's nothing to be assigned there.
inputArray[1] may return null, but if that were happening, your stack trace would not end on this line, it would probably end on some line inside Integer.parseInt. I'd need to see a full stack trace to be sure though. But looking at the javadoc of Integer.parseInt, it doesn't say it'll throw a NPE so that's even more evidence to rule it out.
If inputArray was null, you'd probably get the error on the first if statement so I can rule that out.
Somewhere your code needs to do a obj.nodeList = new NodeList() or something like that. I can't say for sure without seeing what the CHORD class looks like.
This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 10 years ago.
// my first class
public class FirstProject{
int first_number;
public FirstProject(){
first_number = 0;
}
public FirstProject(int Fn){
first_number = Fn;
}
public void Print(){
System.out.println("First number = " + first_number); System.out.println();
}
}
//second class in a separate file
// keep getting an error on this class saying that cannot find the . in p1.print();
public class TestProgram {
public static void main(String[] args){
FirstProject p1 = new FirstProject(10);
p1.print(); System.out.println();
}
Java is case-sensitive:
p1.Print();
But better change
public void Print(){ -> public void print(){
Since methods should not start with a capital letter, according to conventions.
That is simply because you created it as public void Print and are calling it as print. Java is case sensitive ;)
This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 10 years ago.
This is my assignment program in data structure to implement a QueueAsArray. I want someone to guide me about this problem cause I don't have a strong background in java programming.
I'd like someone to give me guidance on what to do to compile and use this code in my main program.
public class QueueAsLinkedList extends AbstractContainer implements Queue
{
protected LinkedList list;
public QueueAsLinkedList ()
{ list = new LinkedList (); }
public void purge ()
{
list.purge ();
count = 0;
}
public Object getHead ()
{
if (count == 0)
throw new ContainerEmptyException ();
return list.getFirst ();
}
public void enqueue (Object object)
{
list.append (object);
++count;
}
public Object dequeue ()
{
if (count == 0)
throw new ContainerEmptyException ();
Object result = list.getFirst ();
list.extract (result);
--count;
return result;
}
public Enumeration getEnumeration()
{
return new Enumeration()
{
protected LinkedList.Element position = list.getHead();
public boolean hasMoreElements()
{
return position != null;
}
public Object nextElement()
{
if (position == null)
throw new NoSuchElementException();
Object result = position.getDatum();
position = position.getNext();
return result;
}
};
}
protected int compareTo (Comparable object)
{
AbstractContainer arg = (AbstractContainer) object;
long diff = (long) getCount() - (long) arg.getCount();
if (diff < 0)
return -1;
else if (diff > 0)
return +1;
else
return 0;
}
public boolean equals(Object object) {
LinkedList list_object = (LinkedList)object;
if(list_object.length != this.length) {
return false;
}
Element ptr = this.head;
Element list_object_ptr = list_object.head;
for(int i = 0; i < this.length; i++) {
if(list_object_ptr.getDatum () != ptr.getDatum ()) {
return false;
}
ptr = ptr.getNext ();
list_object_ptr = list_object_ptr.getNext ();
}
return true;
}
}
My suggestion to you is to read the existing LinkedList libraries source something you can easily find. I suggest you also read the source for ArrayList since you will be wrapping an array. Finally have a look at ArrayBlockingQueue because this is a Queue which wraps an array. This last class is the closest to what you want, but is the most complicated as it is concurrent and thread safe.
When you start writing a class, I suggest you start with something really simple and get that to compile. Using an IDE, it will show you whether the code will compile as you type the code and suggest corrections.
Then I would write a very simple unit test to test your very simple code. You can do this with just one method. (Some people suggest writing the test case first but I find this very hard unless you have written this sort of class before in which case you are not really writing the unit test first, just the first time for that code base)
Then add a second or third method and tests for those.
When it does something you don't understand, use your debugger to step through the code to see what each line does.
I would use an IDE such as Netbeans, Eclipse or IntelliJ CE. I prefer IntelliJ but Netbeans is perhaps the best for a beginner.
Download the IDE.
start a new project.
create a class and copy and paste the code into that class.
create another class which uses that class. This is your class.
BTW Did you write the class or was it given to you because it has more than a few unusual coding choices.
Comments on the code
Its a Queue which wraps a class which implements a Queue so delegation appears natural, but it doesn't appear to do this suggesting that LinkedList and Queue are not the standard LinkedList and Queue which is confusing.
it uses a field count which is not defined instead of the LinkedList.size().
dequeue accesses the LinkedList twice when once would be more efficient (as the standard library does)
It supports Enumeration instead of Iterator when Iterator was been the standard since Java 1.2 (1998)
compareTo is 0 when equals is false which is a bug.
it doen'ts support generics which the builtin one does.
compareTo only examines length so a queue with "A" and a queue with "Z" are compareTo == 0
equals uses this.head and this.length which are not fields.
This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 11 years ago.
In File1.java I have-
public static int[] dataArray = new int[100];
in File2.java I am accessing it as -
private static int[] data = new int[File1.dataArray.length];
for(int i=0; i<File1.dataArray.length; i++) {
if(File1.array1[i] == 0)
continue;
data[i] = File1.array1[i];}
Is this the right way or can I do like this-
private static int[] data = File1.dataArray;
to copy it? Any help appreciated. Thanks!
Yes, you can do
private static int[] data = File1.dataArray;
But there is a HUGE DANGER doing it that way and therefore I wouldn't call it the right way to COPY arrays, because you are not REALLY copying.
See this code. It demonstrates what happens.
public class File1
{
public static int[] dataArray = new int[100];
static
{
for (int i=0; i<100; i++)
{
dataArray[i] = i;
}
}
}
public class File2
{
private static int[] data = File1.dataArray; // makes "data" refer to the SAME array as File1.dataArray
public static void main(String[] args)
{
File2 file2 = new File2();
file2.data[20] = -567; // this changes File1.dataArray also!
System.out.println(File1.dataArray[20]); // prints -567
}
}
Therefore, use System.arrayCopy() to copy arrays, as Jarrod suggested. Of course, you can also copy by writing your own code like this -
private static int[] data = new int[File1.dataArray.length];
static
{
for(int i = 0; i < File1.dataArray.length; i++)
{
data[i] = File1.dataArray[i];
}
}
Look up System.arraycopy() to copy arrays.
It isn't clear what the presented code has to do with Files as referenced in your title?
Also your presented code is incomplete, won't compile and isn't clear or idiomatic Java.
This will most likely get closed if you don't make it clearer what you want to do.