Question
Q: Explain this code package Checkpoint; import static java.lang.Math.floor; /** * * @author toshiba */ public class Sorts implements Sorting{ @Override public void Sorting() {
Q: Explain this code
package Checkpoint; import static java.lang.Math.floor;
/** * * @author toshiba */
public class Sorts implements Sorting{
@Override public void Sorting() { }
@Override /** * Sort the array of strings, v, into ascending lexicographic order using Insertion sort. * No errors may be reported and no exceptions may be thrown. * If an error is detected or an exception occurs, return without modifying the array. * * @param a The array to be sorted. */ public void insertionSort(String[] a) { for (int j = 2; j < a.length; j++) { String key = a[j]; int i = j - 1;
while (i >= 0 && a[i].compareTo(key) > 0) { a[i + 1] = a[i]; i = i - 1; a[i + 1] = key; } } }
@Override /** * Sort the array of {@link strings}, v, into ascending lexicographic order using Merge sort. * No errors may be reported and no exceptions may be thrown. * If an error is detected or an exception occurs, return without modifying the array. * * @param a The array to be sorted. * @param p The left index of the array. * @param r The right index of the array. */ public void mergeSort(String a[], int p, int r) { if (p < r) { int q = (int) floor((p + r) / 2); mergeSort(a, p, q); mergeSort(a, q + 1, r); merge(a, p, q, r); } }
// Merge two sub arrays L and M into array void merge(String array[], int left, int mid, int right) {
int n1 = mid - left + 1; int n2 = right - mid;
String L[] = new String[n1]; String M[] = new String[n2];
// fill the left and right array for (int i = 0; i < n1; i++) { L[i] = array[left + i]; } for (int j = 0; j < n2; j++) { M[j] = array[mid + 1 + j]; }
// Maintain current index of sub-arrays and main array int i, j, k; i = 0; j = 0; k = left;
// Until we reach either end of either L or M, pick larger among // elements L and M and place them in the correct position at A[p..r] // for sorting in descending // use if(L[i] >= <[j]) while (i < n1 && j < n2) { if (L[i].compareTo(M[j]) <= 0) { array[k] = L[i]; i++; } else { array[k] = M[j]; j++; } k++; }
// When we run out of elements in either L or M, // pick up the remaining elements and put in A[p..r] while (i < n1) { array[k] = L[i]; i++; k++; }
while (j < n2) { array[k] = M[j]; j++; k++; } }
}
Step by Step Solution
There are 3 Steps involved in it
Step: 1
Get Instant Access to Expert-Tailored Solutions
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started