October 22, 2024
Chicago 12, Melborne City, USA
java

Trying to create an algorithm to arrange a list of string in an alphabetical order, using Queue Data Structure in Java


I’m new to Java and looking for some advice, I’m learning about Queue Data Structures and trying to create an algorithm that sorts a list of strings into an ascending order. When sorting an array in an ascending order you’d create a key which holds the element of the index from the for loop.

This is the code I function I wrote in C++ that sorts the array of Integers into an ascending order.

int array[] = {38, 27, 43, 3, 9, 82,10};
int length_of_array = sizeof(Test1) / sizeof(Test1[1]);

for(int i = 1; i < length_of_array; i++){
    int key = array[i];
    int j = i - 1;

    while(j >= 0 && array[j] > key){
        array[j + 1] = array[j];
        j--;
    }
    array[j + 1] = key;
}

I’m trying to do a similar thing in Java but using a different Data Structure (queue) and a different set of data (Strings). I’m trying to follow similar principles from the C++ code by creating a for loop and checking each element within the queue and sort them in alphabetical order.

I’m assuming that you’d require a key in the for-loop with the element from the current position. However, I can’t seem to allocate the variable "key" an element from the index point of the loop.

Queue<String> queue = new LinkedList<String>();
        
queue.add("Sam");
queue.add("Mary");
queue.add("James");
queue.add("Sarah");
queue.add("Arnold");
        
for(int i = 1; i < queue.size();i++) {
    String key = queue.get(i);
}

This is what I wrote so far in Java, I’ve tried using queue.element() but realising it will only get the last element from the queue. Tried using .index() and .get() but kept getting an error so I’m not sure how to get the element from the loop.

I know when creating an object of the Queue instead of using LinkedList you can use PriorityQueue which will automatically arrange the list in an ascending order, but I’m trying to create my own algorithm when using LinkedList, is that possible and if so I’d like some advice? Or if there is another better algorithm to write when using Queue.

The reason I’m doing this is because Im currently a university student and one our modules is to do with Algorithms. So I’m trying to figure out an algorithm to sort different Data types in an ascending and descending order, without using the build in Methods such as sort().



You need to sign in to view this answers

Leave feedback about this

  • Quality
  • Price
  • Service

PROS

+
Add Field

CONS

+
Add Field
Choose Image
Choose Video