Question

Need to code the HeapSort Algorithm in java. Most of the code is already done just...

Need to code the HeapSort Algorithm in java. Most of the code is already done just need to code the "heapify" part of the heapsort algorithm. My heapify code is in bold below called "sink", but when I run it it gives me 2 errors with the string compare part saying:

WordCountHeap.java:61: error: cannot find symbol
        if(l < k && String.Compare(pq[l], pq[n]) < 0)
                          ^
symbol:   method Compare(String,String)
location: class String

Please fix the code and the "heapify" portion of the code so it runs without errors and runs the heapsort algorithm correctly.

Code:

import java.io.File;
import java.util.Scanner;
import java.util.Map.Entry;
import java.util.AbstractMap;
import java.util.Arrays;
import java.util.Comparator;

public class WordCountHeap {

   /** Merge two strings. See the textbook for explanation. **/
   public static void merge(String[] S1, String[] S2, String[] S) {
       int i = 0, j = 0;
       while (i + j < S.length) {
           if (j == S2.length || (i < S1.length && S1[i].compareTo(S2[j]) < 0))
               S[i + j] = S1[i++];
           else
               S[i + j] = S2[j++];
       }
   }

   public static void mergeSort(String[] S) {
       int n = S.length;
       if (n < 2)
           return;
       int mid = n / 2;
       // partition the string into two strings
       String[] S1 = Arrays.copyOfRange(S, 0, mid);
       String[] S2 = Arrays.copyOfRange(S, mid, n);
       mergeSort(S1);
       mergeSort(S2);
       merge(S1, S2, S);
   }

   static void constructHeap(String[] a){
        int n = a.length;
        for (int k = n/2; k >= 1; k--)
            sink(a, k,n);
   }

    private static void heapSort(String[] pq) {
        int n = pq.length;
        constructHeap(pq);
        while (n > 1) {
            exch(pq, 1, n);
            n--;
            sink(pq, 1,n);
        }
    }
  
//    private static void sink(String[] pq, int k, int n) {
        //your code goes here
//   }

   private static void sink(String[] pq, int k, int n)
    {
        int largest = n; // Initialize largest as root
        int l = 2*n + 1; // left = 2*n + 1
        int r = 2*n + 2; // right = 2*n + 2

        // If left child is larger than root
        if(l < k && String.Compare(pq[l], pq[n]) < 0)
            largest = l;

        // If right child is larger than largest so far
       if (r < k && String.Compare(pq[r], pq[largest]) < 0)
            largest = r;

        // If largest is not root
        if (largest != n)
        {
            String swap = pq[n];
            pq[n] = pq[largest];
            pq[largest] = swap;

            // Recursively heapify the affected sub-tree
            sink(pq, n, largest);
        }
    }


/** Note that less and exch are defined to offset the 1-based array **/
    private static boolean less(String[] pq, int i, int j) {
        return pq[i-1].compareTo( pq[j-1])<0;
    }

    private static void exch(String[] pq, int i, int j) {
        String swap = pq[i-1];
        pq[i-1] = pq[j-1];
        pq[j-1] = swap;
    }

   private static void swap(String[] array, int i, int j) {
       String tmp = array[i];
       array[i] = array[j];
       array[j] = tmp;
   }

   public static Entry count_ARRAY_SORT(String[] tokens, String sortMethod) {
       int CAPACITY = 1000000;
       String[] words = new String[CAPACITY];
       int[] counts = new int[CAPACITY];
       if (sortMethod.equals("HEAP"))
           heapSort(tokens);
       else if (sortMethod.equals("MERGE"))
           mergeSort(tokens);
       else
           System.out.println(sortMethod + " sorting method does not exist.");

       int j = 0, k = 0;
       int len = tokens.length;
       while (j < len - 1) {
           int duplicates = 1;
           while (j < len - 2 & tokens[j].equals(tokens[j + 1])) {
               j++;
               duplicates++;
           }

           words[k] = tokens[j];
           counts[k] = duplicates;
           j++;
           k++;
       }

       /** get the max count **/
       int maxCount = 0;
       String maxWord = "";
       for (int i = 0; i < CAPACITY & words[i] != null; i++) {
           if (counts[i] > maxCount) {
               maxWord = words[i];
               maxCount = counts[i];
           }
       }
      
//       HeapInt h=new HeapInt(counts);
//       for (int i=0; i<10; i++)
//           System.out.println(h.removeMax());

       return new AbstractMap.SimpleEntry(maxWord, maxCount);
   }

   static String[] readText(String PATH) throws Exception {
       Scanner doc = new Scanner(new File(PATH)).useDelimiter("[^a-zA-Z]+");
       // tokenize text. any characters other than English letters(a-z and A-Z
       // ) are delimiters.
       int length = 0;
       while (doc.hasNext()) {
           doc.next();
           length++;
       }

       String[] tokens = new String[length];
       Scanner s = new Scanner(new File(PATH)).useDelimiter("[^a-zA-Z]+");
       length = 0;
       while (s.hasNext()) {
           tokens[length] = s.next().toLowerCase();
           length++;
       }
       doc.close();
       return tokens;
   }

   public static void main(String[] args) throws Exception {
       String PATH = "/Users/code/dblp";
       String[] METHODS = { "HEAP","MERGE"};
       String[] DATASETS = { "200", "500", "1k", "5k", "10k", "100k", "1m", "" };

       String[] tokens;
       // run the experiments on different data sets
       for (int j = 0; j < 8; j++) {
           // run the experiments using different methods
           System.out.println("Data is " + DATASETS[j]);
           for (int i = 0; i < 2; i++) {
               tokens = readText(PATH + DATASETS[j] + ".txt");
               long startTime = System.currentTimeMillis();
               Entry entry = count_ARRAY_SORT(tokens, METHODS[i]);
               long endTime = System.currentTimeMillis();
               String time = String.format("%12d", endTime - startTime);
               System.out.println(METHODS[i] + " method\t time=" + time + ". Most popular word is " + entry.getKey()
                       + ":" + entry.getValue());
           }
       }
   }
}

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

Maybe you were confused with the sink function's parameters k and n. k is the current index of tokens array whereas n is the total size. You have interchanged them in your code. Below is the updated and correct implementation of sink function.

private static void sink(String[] pq, int k, int n)
{
k--; // 0-based array
int largest = k; // Initialize largest
int l = 2*k + 1; // left = 2*k + 1
ikt r = 2*k + 2; // right = 2*k + 2

// If left child is larger than largest so far
if(l < n && pq[l].compareTo(pq[largest]) > 0)
largest = l;

// If right child is larger than largest so far
if (r < n && pq[r].compareTo(pq[largest]) > 0)
largest = r;

// If largest is changed
if (largest != k)
{
String swap = pq[k];
pq[k] = pq[largest];
pq[largest] = swap;

// Recursively heapify the affected sub-tree
sink(pq, largest+1, n);
}
}

Add a comment
Know the answer?
Add Answer to:
Need to code the HeapSort Algorithm in java. Most of the code is already done just...
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
  • use the same code. but the code needs some modifications. so use this same code and...

    use the same code. but the code needs some modifications. so use this same code and modify it and provide a output Java Program to Implement Merge Sort import java.util.Scanner Class MergeSort public class MergeSort Merge Sort function / public static yoid sortfintfl a, int low, int high) int N-high-low; if (N1) return; int mid- low +N/2; Il recursively sort sort(a, low, mid); sort(a, mid, high); I/ merge two sorted subarrays int] temp new int[N]; int i- low, j-mid; for...

  • Hello, I want to check if my C++ code is correct and follows the requeriments described...

    Hello, I want to check if my C++ code is correct and follows the requeriments described thanks. Requeriments: Assignment Sorting Benchmark each of the sorting methods listed below. Insertion Sort Bubble Sort Selection Sort Heap Sort. Quick Sort. Merge Sort. Benchmark each of the above sorting methods for data sizes of 10000, 20000, 30000, 40000 and 50000. Display the results in a table as shown below. The table should have rows and columns. However, the rows and columns need not...

  • How would I be able to get a Merge Sort to run in this code? MY...

    How would I be able to get a Merge Sort to run in this code? MY CODE: #include <iostream> #include <fstream> #include <stdlib.h> #include <stdio.h> #include <time.h> using namespace std; class mergersorter { private:    float array[1000] ;    int n = 1000;    int i=0; public:    void fillArray()    {        for(i=1;i<=n;i++)        {            array[i-1]= ( rand() % ( 1000) )+1;        }    }    void arrayout ()    {   ...

  • 6. (4 points) The following code for insertion sort has been modified to print out the...

    6. (4 points) The following code for insertion sort has been modified to print out the sorted component of the array during the sort. What will be the output of running the main method of the following code? Try to trace by hand and then verify by executing the code public class Insertion ( public static void sort (String[] a) f int n- a.length; for (int i-1; i < n; i++) f for (int j i; j 0; j--) if...

  • Hello this is my java sorting algorithm program i need all of my errors corrected so...

    Hello this is my java sorting algorithm program i need all of my errors corrected so I can run it. thank you!! import java.util.Scanner;    public class SortingAlogs { public static void main(String[]args){ int array [] = {9,11,15,34,1}; Scanner KB = new Scanner(System.in); int ch; while (true) { System.out.println("1 Bubble sort\n2 Insertion sort\n3 Selection sort\n"); ch = KB.nextInt(); if (ch==1)    bubbleSort(array); if (ch==2)    insertion(array); if (ch==3)    Selection(array); if (ch==4) break;    print(array);    System.out.println(); }    }...

  • Create an ArrayListReview class with one generic type to do the following • Creates an array...

    Create an ArrayListReview class with one generic type to do the following • Creates an array list filled with the generic type of the ArrayListReview class, and inserts new elements into the specified location index-i in the list. (5 points) • Create a method inside the class to implement the calculation of Fibonacci numbers. Use System.nanoTime to find out how much time it takes to get fab(50). Create a method inside the class to check if an array list is...

  • Objective: GUI Layout manager Download one of the sample GUI layout program. Use any GUI layout...

    Objective: GUI Layout manager Download one of the sample GUI layout program. Use any GUI layout to add buttons to start each sort and display the System.nanoTime in common TextArea panel. The question is a bit confusing so i will try to simplify it. Using the GUI ( I made a unclick able one so you have to make it clickable), allow a user to sort the text file based on what they click on. example: if i click merge...

  • USE JAVA PROGRAMMING Create a program that would collect list of persons using double link list...

    USE JAVA PROGRAMMING Create a program that would collect list of persons using double link list and use a Merge Sort to sort the object by age. Create a class called Person : name and age Create methods that add, and delete Person from the link list Create a method that sorts the persons' objects by age. package mergesort; public class MergeSortExample { private static Comparable[] aux; // auxiliary array for merges public static void sort(Comparable[] a) { aux =...

  • Computer Science - Java Explain the code step by step (in detailed order). Also explain what...

    Computer Science - Java Explain the code step by step (in detailed order). Also explain what the program required. Thanks 7 import java.io.File; 8 import java.util.Scanner; 9 import java.util.Arrays; 10 import java.io.FileNotFoundException; 12 public class insertionSort 13 14 public static void insertionSort (double array]) 15 int n -array.length; for (int j-1; j < n; j++) 17 18 19 20 21 double key - array[j]; int i-_1 while ( (i > -1) && ( array [i] > key array [i+1] -...

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