简体   繁体   中英

Quick Sort a Queue with Java

I have a college assignment that I admittedly have waited to the last minute to complete. I thought that I would be able to handle this assignment without any issues but am running into problems. The assignment instructions are as follows.

Write a program that creates a Person class that contains strings that represent the first and last name of a person and their age. You will need to create a Queue class that will store each person in the queue and can sort the queue based on last name or age.

Prompt the user of the program to add five people to the queue. Your program should provide the contents of the queue and then sort the queue using the quick sort in two ways:

Descending order by last name. Descending order by age.

I have already created the Persons Class which will be posted below. I then created a DriverClass which walks the user through creating 5 instances of the Person Class. The problem is that I need to implement a Queue class to store Person Objects. I was thinking about converting the DriverClass into a Queue. But where I run into issues is on the sorting part of the queue. I know there are many different ways to program a queue (linked list, arrays, ext). But what data type will be easiest to perform a quick sort on. And more importantly, I don't know if they want me to perform a quick sort on the queue itself, or the underlying data structure that the queue uses. Any hints on what to do would be great. Thanks! By the way, I am less than 4 months into coding with Java. So the more dumbed down you can make your response, the better. Thanks again everyone.

public class Person {

    private String firstName;
    private String lastName;
    private int age;

    public Person(String firstName, String lastName, int age) {
        setFirstName(firstName);
        setLastName(lastName);
        setAge(age);
    }

    public String getFirstName() {
        return this.firstName;
    }

    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }

    public String getLastName() {
        return this.lastName;
    }

    public void setLastName(String lastName) {
        this.lastName = lastName;
    }

    public int getAge() {
        return this.age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    @Override
    public String toString() {
        return this.firstName + " " + this.lastName + ": " + this.age;
    }
}
import java.util.Scanner;
import java.util.concurrent.TimeUnit;

import static java.lang.Thread.*;

public class DriverClass {

    private static int personCounter = 5;

    public static void main(String[] args) {

        printWelcomeMessage();

        try {
            sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        while(personCounter > 0) {
            addPersonToQueue();
            personCounter -= 1;
        }

    }

    public static void addPersonToQueue() {
        String firstName;
        String lastName;
        int age;

        printInstructions();

        try {
            sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        Scanner userInput = new Scanner(System.in);
        System.out.print("Please enter Person's first mame: ");
        firstName = userInput.nextLine();
        System.out.print("Please enter Person's last name: ");
        lastName = userInput.nextLine();
        System.out.print("Please enter Person's age as a whole number: ");
        age = userInput.nextInt();

        Person newPerson = new Person(firstName, lastName, age);

        try {
            sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    public static void printWelcomeMessage() {
        System.out.println("Hello, welcome to my Module 8 Program...");
    }

    public static void printInstructions() {
        System.out.println("Please add " + personCounter + " Persons to the queue");
    }


}

After much further deliberation I chose to go with an ArrayList as my underlying data structure instead of an Array. I found much better documentation online that could assist with quick sorting from an ArrayList instead of an array.

PERSON CLASS

public class Person {
String firstName;
String lastName;
int personAge;

public Person(){}

public Person(String firstName, String lastName, int personAge) {
    super();
    this.firstName = firstName;
    this.lastName = lastName;
    this.personAge = personAge;
}

public String getFirstName() {
    return this.firstName;
}

public void setFirstName(String firstName) {
    this.firstName = firstName;
}

public String getLastName() {
    return this.lastName;
}

public void setLastName(String lastName) {
    this.lastName = lastName;
}

public int getPersonAge() {
    return this.personAge;
}

public void setPersonAge(int personAge) {
    this.personAge = personAge;
}
}

QUEUE CLASS

import java.util.ArrayList;

public class Queue {
ArrayList<Person> queue;

//choice will decide sort by
//0 - sort by age
// else - sort by last name
int choice;

//default constructor
Queue() {
    queue = new ArrayList<>();
}
//add person to the queue
public void addPerson(Person P) {
    queue.add(P);
}

//partition for quick sort
int partition(ArrayList<Person> queue, int low, int high) {
    if (choice == 0) {
        //pivot will be age
        double pivot = queue.get(high).getPersonAge();
        int i = (low - 1); // index of smaller element
        for (int j = low; j < high; j++) {
            // If current element is smaller than or
            // equal to pivot
            if (queue.get(j).getPersonAge() > pivot) {
                i++;
                //do swap
                Person temp = queue.get(i);
                queue.set(i, queue.get(j));
                queue.set(j, temp);
            }
        }
        //do swap
        Person temp = queue.get(i + 1);
        queue.set(i + 1, queue.get(high));
        queue.set(high, temp);
        return i + 1;
    } else {
        //pivot will be last name
        String pivot = queue.get(high).getLastName();
        int i = (low - 1); // index of smaller element
        for (int j = low; j < high; j++) {
            // If current element is smaller than or
            // equal to pivot
            if (queue.get(j).getLastName().compareTo(pivot) > 0) {
                i++;

                // swap arr[i] and arr[j]
                Person temp = queue.get(i);
                queue.set(i, queue.get(j));
                queue.set(j, temp);
            }
        }

        // swap arr[i+1] and arr[high] (or pivot)
        Person temp = queue.get(i + 1);
        queue.set(i + 1, queue.get(high));
        queue.set(high, temp);
        return i + 1;
    }
}

void sort() {

    //first sort by age
    System.out.println("\n\nORIGINAL QUEUE");
    printQueue();
    choice = 0;
    sortQueue(queue, 0, queue.size() - 1);
    System.out.println("\n\nQUEUE SORTED BY AGE");
    printQueue();
    choice = 1;
    sortQueue(queue, 0, queue.size() - 1);
    System.out.println("\n\nQUEUE SORTED BY LAST NAME");
    printQueue();
}

void sortQueue(ArrayList<Person> queue, int low, int high) {
    if (low < high) {
        // pi is partitioning index, arr[pi] is now at right place
        int pi = partition(queue, low, high);
        // Recursively sort elements before
        // partition and after partition
        sortQueue(queue, low, pi - 1);
        sortQueue(queue, pi + 1, high);
    }
}

//print person list
public void printQueue() {
    for (Person p : queue) {
        System.out.println(p.firstName + " " + p.lastName + " - Age: " + 
p.personAge);
    }
}
}

DRIVER CLASS

import java.util.Scanner;

public class Driver {

public static void main(String args[])

{
    Queue queue = new Queue();
    int counter = 0;
    String firstName;
    String lastName;
    int age;

    Scanner scanner = new Scanner(System.in);
    Scanner scNumber = new Scanner(System.in);

    while(counter < 5) {
        System.out.print("Enter first name of the person : ");
        firstName = scanner.nextLine();
        System.out.print("Enter last name of the person : ");
        lastName = scanner.nextLine();
        System.out.print("Enter age of the person : ");
        age = scanner.nextInt();
        scanner.nextLine();
        Person person = new Person(firstName, lastName, age);
        queue.addPerson(person);
        counter++;
    }

    queue.sort();

    scanner.close();

    scNumber.close();

}

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM