Question

must provide the following public interface: public static void insertSort(int [] arr); public static void selectSort(int...

must provide the following public interface: 
public static void insertSort(int [] arr); 
public static void selectSort(int [] arr);
 public static void quickSort(int [] arr); 
public static void mergeSort(int [] arr); 
The quick sort and merge sort must be implemented by using recursive thinking. So the students may provide the following private static methods: 

//merge method 
//merge two sorted portions of given array arr, namely, from start to middle //and from middle + 1 to end into one sorted portion, namely, from start to end private static void merge(int [] arr, int start, int middle, int end);
//merge sort recursive version 
//sort the portion of giving array arr, from begin to end private static void mergeSortRecursive(int [] arr, int begin, int end);
 //find pivot point for quick sort private static int pivot(int [] arr, int begin, int end);
 //quick sort recursive version 
//sort the portion of giving array arr, from begin to end private static void quickSortRecursive(int [] arr, int begin, int end);
 The student need to have and only have the above public and private static methods in his/her implementation of MySort class.


/**
 * CSCI463ProjOne. This is the main function for Project One.
 * This class is given to students.
 * 
 * @author 
 * @version 
 */
import java.util.*;

public class CSCI463ProjOne
{
    public static final int RANGE = 100000;
    
    /**
     * Randomly fill up the given array with integers from 0 to 100000
     */
    public static void fillArray(int [] arr)
    {
        Random randGen = new Random();
        for(int i = 0; i < arr.length; i++)
            arr[i] = randGen.nextInt(RANGE);
    }
    
    /**
     * copy the content in second array to first array. We assume 
     * two array has same size
     * @param firstArray the destination of copy action
     * @param secondArray the source of copy action
     */
    public static void copy(int [] firstArray, int [] secondArray)
    {
        for(int i = 0; i < secondArray.length; i++)
            firstArray[i] = secondArray[i];
    }
    /**
     * isSorted
     * @return true if the array is sorted from least to largest
     * or is sorted from largest to least
     */
    public static boolean isSorted(int [] arr)
    {
        if(arr.length <= 1) return true;
        int index = 0;
        while(index < arr.length-1 && arr[index] == arr[index+1])
        {
            index++;
        }
        // bypass first equal elements
        if(index == arr.length - 1) return true; // all elements are the same
        else if(index < arr.length - 1 && arr[index] > arr[index+1]) // possible descend
        {
            for(int i = index+2; i < arr.length; i++)
                if(arr[i] > arr[i-1]) return false;
        }
        else // sort for ascend
        {
             for(int i = index+2; i < arr.length; i++)
                if(arr[i] < arr[i-1]) return false;
        }
        
        return true;
    }
    
    /**
     * test the sort with given array. The test array will not be modified
     * @param arr The array that is used to test the sort. The array will not be modified
     * @name The name of sort method that is to be tested
     */
    public static void testSort(int [] arr, String name)
    {
        long totalTime = 0;
        int [] a = new int[arr.length];
        copy(a, arr); // copy arr to a
        
        // get start time
        long start = Calendar.getInstance().getTimeInMillis();
        if(name.equals("Insert Sort"))
            MySorts.insertSort(a);
        else if(name.equals("Select Sort"))
            MySorts.selectSort(a);
        else if(name.equals("Quick Sort"))
            MySorts.quickSort(a);
        else if(name.equals("Merge Sort"))
            MySorts.mergeSort(a);
            
        long end = Calendar.getInstance().getTimeInMillis();
        if(isSorted(a)){
            totalTime = end - start;
            System.out.println("Execution time for " + name + " is: " + totalTime + " milliseconds");
        }
        else
            System.out.println("The " + name + " did not work properly");
    }
    
    /**
     * display the test menu
     */
    public static void displayMenu()
    {
        System.out.println("***************************");
        System.out.println("*          MENU           *");
        System.out.println("* 1. Fill Array           *");
        System.out.println("* 2. Select Sort          *");
        System.out.println("* 3. Insert Sort          *");
        System.out.println("* 4. Quick Sort           *");
        System.out.println("* 5. Merge Sort           *");
        System.out.println("* 6. Quit                 *");
        System.out.println("***************************");
    }
    
    public static void main(String [] args){
        int choice;
        int [] arr = new int[RANGE];
        
        Scanner input = new Scanner(System.in);
        do{
            displayMenu();
            System.out.println("Enter you choice: ");
            choice = input.nextInt();
            switch(choice){
                case 1: // generate a new random filled array
                    fillArray(arr);
                    break;
                case 2: // select sort
                    testSort(arr, "Select Sort");
                    break;
                case 3: // insert sort
                    testSort(arr, "Insert Sort");
                    break;
                case 4: // quick sort
                    testSort(arr, "Quick Sort");
                    break;
                case 5: // merge sort
                    testSort(arr, "Merge Sort");
                    break;
                case 6: // quit
                    System.out.println("Make sure that you have good documentation!");
                    break;
                default: // wrong choice
                    
            }
            
        }while(choice != 6);
    }
   
}
0 0
Add a comment Improve this question Transcribed image text
Answer #1

public class Main {

/*
Method to sort array data using selection sort
arr[] --> Array to be sorted
*/
public static void selectSort(int[] arr) {

for (int i = 0; i < arr.length - 1; i++) {
int index = i;
for (int j = i + 1; j < arr.length; j++)
if (arr[j] < arr[index])
index = j;

int smallerNumber = arr[index];
arr[index] = arr[i];
arr[i] = smallerNumber;
}
return;
}
/*
Method to sort array data using insertion sort
arr[] --> Array to be sorted
*/
public static int[] insertSort(int[] input) {

int temp;
for (int i = 1; i < input.length; i++) {
for (int j = i; j > 0; j--) {
if (input[j] < input[j - 1]) {
temp = input[j];
input[j] = input[j - 1];
input[j - 1] = temp;
}
}
}
return input;
}

/* Pivot and partitioning function: Takes last element as pivot,places the pivot element at its correct
position in sorted array, and places all smaller (smaller than pivot) to left of pivot and all greater elements to right
of pivot */
private static int pivot(int arr[], int low, int high) {
int pivot = arr[high];
int i = (low - 1); // index of smaller element
for (int j = low; j < high; j++) {
// If current element is smaller than or
// equal to pivot
if (arr[j] <= pivot) {
i++;

// swap arr[i] and arr[j]
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}

// swap arr[i+1] and arr[high] (or pivot)
int temp = arr[i + 1];
arr[i + 1] = arr[high];
arr[high] = temp;

return i + 1;
}


/* The main function that implements QuickSort()
arr[] --> Array to be sorted,
low --> Starting index,
high --> Ending index */
public static void quickSortRecursive(int arr[], int low, int high) {
if (low < high) {
/* pi is partitioning index, arr[pi] is
now at right place */
int pi = pivot(arr, low, high);

// Recursively sort elements before
// partition and after partition
quickSortRecursive(arr, low, pi - 1);
quickSortRecursive(arr, pi + 1, high);
}
}

// merge two sorted portions of given array arr, namely, from start to middle
// and from middle + 1 to end into one sorted portion, namely, from start to end
// First subarray is arr[l..m]
// Second subarray is arr[m+1..r]
private static void merge(int arr[], int l, int m, int r) {
int i, j, k;
int n1 = m - l + 1;
int n2 = r - m;

/* create temp arrays */
int L[] = new int[n1];
int R[] = new int[n2];

/* Copy data to temp arrays L[] and R[] */
for (i = 0; i < n1; i++)
L[i] = arr[l + i];
for (j = 0; j < n2; j++)
R[j] = arr[m + 1 + j];

/* Merge the temp arrays back into arr[l..r]*/
i = 0; // Initial index of first subarray
j = 0; // Initial index of second subarray
k = l; // Initial index of merged subarray
while (i < n1 && j < n2) {
if (L[i] <= R[j]) {
arr[k] = L[i];
i++;
} else {
arr[k] = R[j];
j++;
}
k++;
}

/* Copy the remaining elements of L[], if there
are any */
while (i < n1) {
arr[k] = L[i];
i++;
k++;
}

/* Copy the remaining elements of R[], if there
are any */
while (j < n2) {
arr[k] = R[j];
j++;
k++;
}
}

/* l is for left index and r is right index of the
sub-array of arr to be sorted */
public static void mergeSortRecursive(int arr[], int l, int r) {
if (l < r) {
// Same as (l+r)/2, but avoids overflow for
// large l and h
int m = l + (r - l) / 2;

// Sort first and second halves
mergeSortRecursive(arr, l, m);
mergeSortRecursive(arr, m + 1, r);

merge(arr, l, m, r);
}
}
/*
Main method
*/
public static void main(String a[]) {
System.out.print("Selection sort results:\n ");
int[] arr1 = {24,2,45,20,56,75,2,56,99,53,12};
selectSort(arr1);
for (int i: arr1) {
System.out.print(i);
System.out.print(", ");
}
System.out.print("\nInsertion sort results:\n ");
int[] arr2 = {10,34,2,56,7,67,88,42};
insertSort(arr2);
for (int i: arr2) {
System.out.print(i);
System.out.print(", ");
}
int arr3[] = {10, 7, 8, 9, 1, 5};
int n = arr3.length;
System.out.print("\nQuick sort results:\n ");
quickSortRecursive(arr3, 0, n - 1);
for (int i: arr3) {
System.out.print(i);
System.out.print(", ");
}
  
int arr4[] = {12, 11, 13, 5, 6, 7};
int arr_size = arr4.length;
System.out.print("\nMerge sort results:\n ");
mergeSortRecursive(arr4, 0, arr_size - 1);
for (int i: arr4) {
System.out.print(i);
System.out.print(", ");
}
}
}

Add a comment
Know the answer?
Add Answer to:
must provide the following public interface: public static void insertSort(int [] arr); public static void selectSort(int...
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
  • import java.util.Arrays; public class lab {    public static void main(String args[])    {    int...

    import java.util.Arrays; public class lab {    public static void main(String args[])    {    int arr[] = {10, 7, 8, 9, 1, 5,6,7};    int arr2[] = {9, 8, 7, 6, 5, 4, 3, 2, 1};    int arr3[] = {1, 3, 5, 3, 2, 6, 20};    quicksort(arr,0,arr.length-1);    quicksort(arr2,0,arr2.length-1);    quicksort(arr3,0,arr3.length-1);    System.out.println(Arrays.toString(arr));    System.out.println(Arrays.toString(arr2));    System.out.println(Arrays.toString(arr3));       }    private static int partition(int[] items,int low, int high)    {    int i=0;    int j=0;...

  • 5. What is the Big Oh method m2? public static void m2(int[] arr, int n) for...

    5. What is the Big Oh method m2? public static void m2(int[] arr, int n) for (int í = 1; í <= n- 1; i++) pM2(arr [i], arr, 0, i - 1); // end m2 private static void pM2(int entry, int[l arr, int begin, int end) int i- end; for(; (i 〉= begin) && (entry 〈 arr [i]); i--) arr [1 + 1] = arr L1] arr[i + 1] - entry; return // end pM2

  • Our 1st new array operation/method is remove. Implement as follows: public static boolean remove( int[] arr,...

    Our 1st new array operation/method is remove. Implement as follows: public static boolean remove( int[] arr, int count, int key ) { 1: find the index of the first occurance of key. By first occurance we mean lowest index that contains this value. hint: copy the indexOf() method from Lab#3 into the bottom of this project file and call it from inside this remove method. The you will have the index of the value to remove from the array 2:...

  • I need to program 3 and add to program 2 bellows: Add the merge sort and...

    I need to program 3 and add to program 2 bellows: Add the merge sort and quick sort to program 2 and do the same timings, now with all 5 sorts and a 100,000 element array. Display the timing results from the sorts. DO NOT display the array. ____________________>>>>>>>>>>>>>>>>>>>>___________________________ (This is program 2 code that I did : ) ---->>>>>> code bellow from program 2 java program - Algorithms Write a program that randomly generates 100,000 integers into an array....

  • Your running times will probably be different than these. Please do a better job with the snipping tool than I did. Jav...

    Your running times will probably be different than these. Please do a better job with the snipping tool than I did. Java program provided: // Student Name Today's Date import java.util.Arrays; import java.util.Random; public class SortTimer {    // Please expand method main() to meet the lab requirements.       // You have the following sorting methods available:    // insertionSort(int[] a);    // selectionSort(int[] a);    // mergeSort(int[] a);    // quickSort(int[] a);    // The array will be in sorted order after the routines are called!   ...

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

  • I have a multithreaded java sorting program that works as follows: 1. A list of double...

    I have a multithreaded java sorting program that works as follows: 1. A list of double values is divided into two smaller lists of equal size 2. Two separate threads (which we will term sorting threads) sort each sublist using a sorting algorithm of your choice 3. The two sublists are then merged by a third thread merging thread that merges the two sublists into a single sorted list. SIMPLE EXECUTION >java SortParallel 1000 Sorting is done in 8.172561ms when...

  • COMPLETE THE BUCKETSORT METHOD public static void bucketSort(int[] array) {        int bucketCount = array.length/2;...

    COMPLETE THE BUCKETSORT METHOD public static void bucketSort(int[] array) {        int bucketCount = array.length/2;        int minIntValue = 0;        int maxIntValue = array.length - 1;        // Create bucket array        List<Integer>[] buckets = new List[bucketCount];        // Associate a list with each index in the bucket array           for(int i = 0; i < bucketCount; i++){            buckets[i] = new LinkedList<>();        }        //...

  • Implement merge sort and merge #include <iostream> using namespace std; void * merge(int arr[], int start1, int end1, int start2, int end2){ int * combined = new int[end2-start1 + 1];         ...

    Implement merge sort and merge #include <iostream> using namespace std; void * merge(int arr[], int start1, int end1, int start2, int end2){ int * combined = new int[end2-start1 + 1];             } void mergeSort(int arr[], int start, int end){ //base case: down to 1 item, do nothing //recursive case: //MergeSort(left) //MergeSort(right) //Merge(left, right) int m = (end - start) / 2; if(start==end){ } else { mergeSort(arr, start, m); mergeSort(arr, m+1, end); merge(arr, start, m, m+1, end); } } void fill(int arr[],...

  • public static int max(int [] arr){ int max = arr[0]; for( int i = 1; i...

    public static int max(int [] arr){ int max = arr[0]; for( int i = 1; i < arr.length; i++ ) if( arr[i] > max ) max = arr[i]; return max; } 1) Provide an input value for arr that causes the method to throw an IndexOutOfBounds exception. 2) Provide an input value for arr that causes the method to throw a NullPointerException.

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