Question

Revise the Shell sort so that it could process SLL Note: process linked list Node rather...

Revise the Shell sort so that it could process SLL

Note: process linked list Node rather than just processing an array of data of the Single link list

Gap: h/2 for Shell Sort

Any help would be appreciated

0 0
Add a comment Improve this question Transcribed image text
Answer #1

Disclaimer: I would suggest you to calmly read the solution I'm providing to you because this is a hard and complex problem!!.

So you need to devote some time to understand it because it also uses the bubble sort algorithm with the Shell sort algorithm and the code which I have written is lengthy.

Thank You.

here is the Java Implementation of the problem


import java.io.PrintWriter;

public class Sorting {

    private static int pass;
    private static int cmp;
    private static int exch;
    private static int length;

    private static int totalPass;
    private static int totalCmp;
    private static int totalExch;

    private static long duration;
    private static PrintWriter writer;


    /**
     * Constructs a sort object and initializes values.
     *
     * @param theLength the length of a linked list.
     * @param theWriter the writer object to write data to a file.
     */
    public Sorting(int theLength, PrintWriter theWriter) {
        length = theLength;
        pass = 0;
        cmp = 0;
        exch = 0;

        totalPass = 0;
        totalCmp = 0;
        totalExch = 0;

        duration = 0;
        writer = theWriter;
    }

    /**
     * Sort a linked list using Bubble Sort algorithm.
     *
     * @param head the reference to the first node.
     */
    public void bubbleSort(Node head) {

        Node previous;   // Previous element of the current
        Node current;    // Current element to compare
        Node comparable; // Next element to compare

        boolean swapped = true;

        bubblePrintAndWriteResults(head, false);

        // start time to calculate sorting time in milli seconds
        long startTime = System.nanoTime();

        // Check if none of the element have been swaped
        // Indicates that the list is sorted.
        while (swapped) {
            cmp = 0;
            exch = 0;

            previous = head;
            current = head.getNext();
            comparable = head.getNext().getNext();
            swapped = false;

            while (comparable != null) {
                cmp++;

                // swap compared nodes
                if (current.getData() > comparable.getData()) {

                    bubbleSwapNodes(current, comparable, previous);
                    current = previous.getNext();
                    comparable = previous.getNext().getNext();

                    exch++;
                    swapped = true;

                }

                // move nodes to the next positions
                previous = previous.getNext();
                current = current.getNext();
                comparable = comparable.getNext();
            }

            pass++;
            totalPass++;
            totalExch += exch;
            totalCmp += cmp;

            if (exch != 0) {
                bubblePrintAndWriteResults(head, false);
            }
        }
        // end time to calculate sorting time in milli seconds
        long endTime = System.nanoTime();

        // sorting time in milli seconds
        duration = (endTime - startTime) / 1000000;

        bubblePrintAndWriteResults(head, true);
    }

    /**
     * Sort a linked list using Shell Sort algorithm.
     *
     * @param head the reference to the first node.
     */
    public void shellSort(Node head) {

        resetCounts();

        Node current;    // Current element to compare
        Node comparable; // Next element to compare
        Node lprev;      // Previous node of the current
        Node rprev;      // Previous node of the comparable

        boolean swapped = true;

        int index = 0;
        int extra = 0;
        double k = 0;

        long startTime = System.nanoTime();

        // find the proper K value
        while (((Math.pow(3, index) - 1) / 2) < length) {
            k = (Math.pow(3, index) - 1) / 2;
            ++index;
        }
        index--;

        shellPrintAndWriteResults(head, k, extra, false);

        // compare elements with the K value larger than 1
        while (k > 1) {

            swapped = true;

            current = head.getNext();
            comparable = head.getNext();
            lprev = head;
            rprev = head;

            for (int i = 0; i < k; i++) {
                rprev = comparable;
                comparable = comparable.getNext();
            }

            extra = length - (int) k;

            // Check if none of the element have been swapped
            // Indicates that the list is sorted for the given K.
            while (swapped) {
                swapped = false;

                while (comparable != null) {
                    cmp++;

                    // compare two numbers: current > comparable
                    if (current.getData() > comparable.getData()) {

                        shellSwapNodes(current, comparable, lprev, rprev);

                        // move nodes to the next position
                        lprev = lprev.getNext();
                        rprev = rprev.getNext();
                        current = lprev.getNext();
                        comparable = rprev.getNext();

                        swapped = true;
                        exch++;
                    }

                    // move nodes to the next positions
                    else {
                        lprev = lprev.getNext();
                        rprev = rprev.getNext();
                        current = lprev.getNext();
                        comparable = rprev.getNext();
                    }
                }
                pass++;

                // move the list back to the beginning
                current = head.getNext();
                comparable = head.getNext();
                lprev = head;
                rprev = head;

                // set comparable to N nodes ahead
                for (int i = 0; i < k; i++) {
                    rprev = comparable;
                    comparable = comparable.getNext();
                }

            }

            shellPrintAndWriteResults(head, k, extra, false);

            pass -= 1;
            totalPass += pass;
            totalCmp += cmp-extra;
            totalExch += exch;

            // make k value lower
            k = (Math.pow(3, --index) - 1) / 2;
            extra = length - (int) k;

        }

        // for K value equal to 1, just do bubble sort with a helper method.
        if (k == 1) {
            shellBubbleSort(head, extra, startTime);
        }

    }


    /**
     * Swap the given nodes for the Shell Sort algorithm.
     *
     * @param current the current node to compare
     * @param comparable the next element to compare with current.
     * @param lprev the previous element of the current.
     * @param rprev the previous element of comparable.
     */
    private void shellSwapNodes(Node current, Node comparable, Node lprev, Node rprev) {
        rprev.setNext(comparable.getNext());
        comparable.setNext(current.getNext());
        lprev.setNext(comparable);
        current.setNext(rprev.getNext());
        rprev.setNext(current);
    }

    /**
     * Swap the given nodes for the Bubble Sort algorithm.
     * @param current the current node to compare
     * @param comparable the next element to compare with current.
     * @param prev the previous element of the current.
     */
    private void bubbleSwapNodes(Node current, Node comparable, Node prev) {
        current.setNext(comparable.getNext());
        comparable.setNext(current);
        prev.setNext(comparable);
    }

    /**
     * Reset static counts variables.
     */
    private void resetCounts() {
        pass = 0;
        cmp = 0;
        exch = 0;

        totalPass = 0;
        totalCmp = 0;
        totalExch = 0;

        duration = 0;
    }

    /**
     * Helper method for the shell sort algorithm for the final stage.
     *
     * @param head a reference to the first node.
     * @param extra an extra iteration value when list is sorted.
     * @param startTime start time to calculate sorting time
     */
    private void shellBubbleSort(Node head, int extra, long startTime) {

        pass = 0;
        cmp = 0;
        exch = 0;

        int k = 1;

        boolean swapped = true;

        Node prev;
        Node current;
        Node comparable;

        while (swapped) {

            prev = head;
            current = head.getNext();
            comparable = head.getNext().getNext();
            swapped = false;

            while (comparable != null) {

                cmp++;

                if (current.getData() > comparable.getData()) {

                    bubbleSwapNodes(current, comparable, prev);

                    current = prev.getNext();
                    comparable = prev.getNext().getNext();
                    swapped = true;
                    exch++;
                }

                // move nodes to the next positions
                prev = prev.getNext();
                current = current.getNext();
                comparable = comparable.getNext();
            }
            pass++;

        }

        pass -= 1;
        totalPass += pass;
        totalCmp += (cmp - extra);
        totalExch += exch;

        long endTime = System.nanoTime();
        duration = (endTime - startTime) / 1000000;

        shellPrintAndWriteResults(head, k, extra, true);
    }

    /**
     * Helper method for Shell Sort algorithm to print and writ output of the intermediate stages.
     *
     * @param head a reference to the first node.
     * @param complete trigger to print total results.
     */
    private void bubblePrintAndWriteResults(Node head, boolean complete) {

        if (pass == 0) {
            if (length <= 20) {
                System.out.printf("\nBUBBLE SORT RESULTS\n");
                System.out.printf("===================\n");
                System.out.printf("        pass       cmp      exch      time   ");
                System.out.printf("%-80s\n", head.getNext().toString());

                writer.printf("\nBUBBLE SORT RESULTS\n");
                writer.printf("===================\n");
                writer.printf("        pass       cmp      exch      time   ");
                writer.printf("%-80s\n", head.getNext().toString());
            } else {
                System.out.printf("\nBUBBLE SORT RESULTS\n");
                System.out.printf("===================\n");
                System.out.printf("      pass       cmp      exch      time    \n");

                writer.printf("\nBUBBLE SORT RESULTS\n");
                writer.printf("===================\n");
                writer.printf("      pass       cmp      exch      time    \n");
            }
            System.out.println("------------------------------------------");
            writer.println("------------------------------------------");

        } else {
            if (length <= 20) {
                System.out.printf("%9d %10d %8d %14s %-65s\n", pass, cmp, exch, " ", head.getNext().toString());
                writer.printf("%9d %10d %8d %14s %-65s\n", pass, cmp, exch, " ", head.getNext().toString());
            }

        }

        // print and write totals
        if (complete) {
            if (length <= 20)
                System.out.println("------------------------------------------");
            System.out.printf("Total %3d %10d %8d %8d ms\n\n", totalPass, totalCmp, totalExch, duration);
            if (length <= 20)
                writer.println("------------------------------------------");
            writer.printf("Total %3d %10d %8d %8d ms\n\n", totalPass, totalCmp, totalExch, duration);
        }

    }

    /**
     * Helper method for Shell Sort algorithm to print and writ output of the intermediate stages.
     *
     * @param head a reference to the first node.
     * @param complete trigger to print total results.
     */
    private void shellPrintAndWriteResults(Node head, double k, int shift, boolean complete) {

        if (pass == 0) {

            if (length <= 20) {
                System.out.printf("SHELL SORT RESULTS\n");
                System.out.printf("===================\n");
                System.out.printf("      k  pass       cmp      exch      time    ");
                System.out.printf("%-84s\n", head.getNext().toString());

                writer.printf("\nSHELL SORT RESULTS\n");
                writer.printf("===================\n");
                writer.printf("      k  pass       cmp      exch      time    ");
                writer.printf("%-84s\n", head.getNext().toString());
            }
            else {
                System.out.printf("SHELL SORT RESULTS\n");
                System.out.printf("===================\n");
                System.out.printf("      k  pass       cmp      exch      time    \n");

                writer.printf("\nSHELL SORT RESULTS\n");
                writer.printf("===================\n");
                writer.printf("      k  pass       cmp      exch      time    \n");
            }
            System.out.println("-------------------------------------------");
            writer.println("-------------------------------------------");

        } else {
            for (int i = 1; i < pass; i++) {

                if (length <= 20) {
                    if (i == (pass - 1)) {
                        System.out.printf("%7d %3d %10d %8d %14s %-65s\n", (int) k, i, cmp - shift, exch, " ", head.getNext().toString());
                        writer.printf("%7d %3d %10d %8d %14s %-65s\n", (int) k, i, cmp - shift, exch, " ", head.getNext().toString());
                    }
                    else {
                        System.out.printf("%7d %3d %34s %-85s\n", (int) k, i, " ", head.getNext().toString());
                        writer.printf("%7d %3d %34s %-85s\n", (int) k, i, " ", head.getNext().toString());
                    }

                } else {

                    if (i == (pass - 1)) {
                        System.out.printf("%7d %3d %10d %8d\n", (int) k, i, cmp - shift, exch);
                        writer.printf("%7d %3d %10d %8d\n", (int) k, i, cmp - shift, exch);
                    }
                }
            }
        }

        // print and write totals
        if (complete) {
            System.out.println("-------------------------------------------");
            System.out.printf("  Total %3d %10d %8d %8d ms\n\n", totalPass, totalCmp, totalExch, duration);

            writer.println("-------------------------------------------");
            writer.printf("  Total %3d %10d %8d %8d ms\n\n", totalPass, totalCmp, totalExch, duration);
        }
    }

}

---------------------------------------------------------------------------------------

As mentioned above try to read the solution properly and try to dry run it on the paper once you understand it you can implement it yourself then it would be easy.

If you are satisfied with the answer then do give it a thumbs up and support teachers/Mentors like us in these pandemic situations

If you come across any doubt feel free to ask in the comments.

Thanks a Lot.

ALL THE BEST!!

Happy Learning.

Add a comment
Know the answer?
Add Answer to:
Revise the Shell sort so that it could process SLL Note: process linked list Node rather...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • Redo the insertionsort algorithm so that the values are inserted into a linked list rather than...

    Redo the insertionsort algorithm so that the values are inserted into a linked list rather than an array. This eliminates the need to move other values when a new value is inserted, since your algorithm can simply insert a new node where the new value should go. Analyze your algo- rithm to obtain a big-O expression of the worst-case running time. Code your algorithm to produce a complete C++ program that reads in a list of 10 in- tegers, sorts...

  • I need this in C++. This is all one question Program 2: Linked List Class For...

    I need this in C++. This is all one question Program 2: Linked List Class For this problem, let us take the linked list we wrote in a functional manner in a previous assignment and convert it into a Linked List class. For extra practice with pointers we'll expand its functionality and make it a doubly linked list with the ability to traverse in both directions. Since the list is doubly linked, each node will have the following structure: struct...

  • In this assignment you are to utilize the Node data structure provided on Blackboard. In this...

    In this assignment you are to utilize the Node data structure provided on Blackboard. In this assignmet you are to write a main program that implements two methods and a main method as their driver. So, only main and two methods with it. Note: You may not use any of the LinkedList class provided on Blackboard, you may use the methods in it as a guide (you should actually look at them) but you cannot use any of the methods...

  • Using Python. 3) Create a single-linked list (StudentList) where the data in the link is an object of type pointer to Student as defined below. Note that you need to store and pass a pointer of type...

    Using Python. 3) Create a single-linked list (StudentList) where the data in the link is an object of type pointer to Student as defined below. Note that you need to store and pass a pointer of type Student so that you do not create duplicate objects. Test your list with the provided program. You will find example code for a single-linked list of integers in Moodle that you can base your solution on. For your find methods, you can either...

  • I need help implemeting the remove_repetitions() Here is a brief outline of an algorithm: A node...

    I need help implemeting the remove_repetitions() Here is a brief outline of an algorithm: A node pointer p steps through the bag For each Item, define a new pointer q equal to p While the q is not the last Item in the bag If the next Item has data equal to the data in p, remove the next Item Otherwise move q to the next Item in the bag. I also need help creating a test program _____________________________________________________________________________________________________________________________________________________ #ifndef...

  • 8.9 Coding lab #5: create a dynamic array ADT and a singly linked list ADT. Honor Code...

    8.9 Coding lab #5: create a dynamic array ADT and a singly linked list ADT. Honor Code Your answers to this homework must be your own work.You are not allowed to share your solutions.You may not engage in any other activities that will dishonestly improve your results or dishonestly improve or damage the results of others. Plagiarism Plagiarism is when you copy words, ideas, or any other materials from another source without giving credit. Plagiarism is unacceptable in any academic environment....

  • Part 1: Implement a singly linked list -------------------------------------- (a) Your job is to implement a generic...

    Part 1: Implement a singly linked list -------------------------------------- (a) Your job is to implement a generic singly linked list that can hold any data type. The interface has been specified and provided to you in a header file called mylist.h. So your job is to write mylist.c that implements each function whose prototype is included in mylist.h. Specifically, you are asked to write the following functions: struct Node *addFront(struct List *list, void *data) void traverseList(struct List *list, void (*f)(void *))...

  • must be coded in c++ without any STL libraries sadly :( so im struggling on this...

    must be coded in c++ without any STL libraries sadly :( so im struggling on this problem, any help would be greatly appreciated, thanks in advance! :) assignment is due tomorrow and im really struggling on this last question :( a. Begin by implementing a BST for integers. The underlying structure is a linked list. You need these methods: i. BST(); -- Constructor ii. void put (int) – Inserts a value into the BST. iii. Void put(int[] a) – Inserts...

  • a. b. c. If the client requests the removal of a single node in a general...

    a. b. c. If the client requests the removal of a single node in a general tree (a tree with no limit on the number of children per node) as we have studied it, this might result in many more nodes than the one requested to be removed (from the client's perspective) While the answer will be the same for normal and lazy deletion, you can assume this tree does normal, not lazy, deletion, to avoid unnecessary thinking time. O...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT