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...

  • Need some help creating a bubble sort for my linked list in C. Here are the...

    Need some help creating a bubble sort for my linked list in C. Here are the structs used in my code: struct simulation {    void *list;    int et; /* in seconds */ }; struct plane {    double x, y, altitude;    char callsign[15];    struct simulation *sim; }; Here is the struct used in my linked list: struct Node {    void *data;    struct Node *next; }; Here is my insert function: //ComparisonFunction and FILE not...

  • Programming Assignment 1 Data structure Java Implement Shellsort for a linked list, based on a variant...

    Programming Assignment 1 Data structure Java Implement Shellsort for a linked list, based on a variant of bubble sort. The rather severe constraints imposed by the singly-linked list organization presents special problems for implementing Shellsort. Your task is to overcome these constraints and develop a simple, elegant implementation that does not sacrifice efficiency or waste space. Step 1. First, implement a routine to build a list: read integers from standard input, and build a list node for each item consisting...

  • In C++, Modify the following code of a single linked list, so insted of doing sort...

    In C++, Modify the following code of a single linked list, so insted of doing sort insert in descending order, to do it in ascending order: template <class T> void IntSLList<T>::sortInsert(T val) {    //if empty the list    if (head == 0)    {        //add as node to head with data as val        addToHead(val);    }    //if not empty    else    {        //create to pointers to the list        IntSLLNode<T>...

  • Creating linked list data structure Overview The purpose of this assignment is for you to write...

    Creating linked list data structure Overview The purpose of this assignment is for you to write a data structure called a Linked List, which utilizes templates (similar to Java’s generics), in order to store any type of data. In addition, the nature of a Linked List will give you some experience dealing with non-contiguous memory organization. This will also give you more experience using pointers and memory management. Pointers, memory allocation, and understand how data is stored in memory will...

  • c++ only Program 2: Linked List Class For this problem, let us take the linked list...

    c++ only 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 Node { int number; Node * nextNode;...

  • 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...

  • C++ Linked List Implementation Motivation As we discussed in class, the data structures that you use...

    C++ Linked List Implementation Motivation As we discussed in class, the data structures that you use to implement your program can have a profound impact on it's overall performance. A poorly written program will often need much more RAM and CPU time then a well-written implementation. One of the most basic data structure questions revolves around the difference between an array and a linked list. After you finish this assignment you should have a firm understanding of their operation. Problem...

  • 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...

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