Write Code In Java Heap Sorting “F” words This exam is OPEN BOOK, OPEN NOTE, AND
ID: 3689051 • Letter: W
Question
Write Code In Java
Heap Sorting “F” words
This exam is OPEN BOOK, OPEN NOTE, AND OPEN INERNET. We are allowed to answer questions, but we are not allowed to give advice or help. This is due at the end of the lab session. Good Luck!
Objective:
Write a program that heap sorts an arbitrary number of words or sentences from the least number of F’s (ignoring case) in the word to the most number of F’s in the word. Write a frontend in that will take in each word or phrase, and then sort and prints them.
Example Dialog:
Welcome to the F word sorter! Enter words or phrases and it will sort from least number of F’s to the most number of F’s. Enter “Sort” to finish and sort.
FUN
Fluffy
Fife
Five Dollar Foot Long For Five Dollars
FfffFFffuuu!
Farmer Fred Fiddles for Food
After Friday fear the final. Be afraid friend.
Sort
The sorted phrases are
FUN
Fife
Fluffy
Five Dollar Foot Long For Five Dollars
Farmer Fred Fiddles for Food
After Friday fear the final. Be afraid friend.
FfffFFffuuu!
Explanation / Answer
import java.util.ArrayList; import java.util.Scanner; /* Class HeapSort */ class HeapSort { private static int N; /* Sort Function */ public static void sort(String arr[]) { heapify(arr); for (int i = N; i > 0; i--) { swap(arr,0, i); N = N-1; maxheap(arr, 0); } } /* Function to build a heap */ public static void heapify(String arr[]) { N = arr.length-1; for (int i = N/2; i >= 0; i--) maxheap(arr, i); } /* Function to swap largest element in heap */ public static void maxheap(String arr[], int i) { int left = 2*i ; int right = 2*i + 1; int max = i; if (left countF(arr[i])) max = left; if (right countF(arr[max])) max = right; if (max != i) { swap(arr, i, max); maxheap(arr, max); } } public static int countF(String s){ int c = 0; for(char ch : s.toCharArray()){ if(ch=='f'||ch=='F') c++; } return c; } /* Function to swap two elements in an array */ public static void swap(String arr[], int i, int j) { String tmp = arr[i]; arr[i] = arr[j]; arr[j] = tmp; } /* Main method */ public static void main(String[] args) { Scanner scan = new Scanner( System.in ); int n=0, i; ArrayList strings = new ArrayList(); System.out.println(" Enter elements"); for (i = 0; ; i++) { String s = scan.nextLine(); if(s.equalsIgnoreCase("sort")){ break; } strings.add(s); n++; } String arr[] = new String[n]; arr = strings.toArray(arr); sort(arr); System.out.println(" Elements after sorting "); for (i = 0; iRelated Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.