Question

In: Computer Science

the language that suggested is java - Given the following sorting techniques, that uses the algorithmic...

the language that suggested is java

- Given the following sorting techniques, that uses the algorithmic design techniques of Induction and Divide and Conquer paradigm:

a. Quicksort using pivot as the maximum element

b. Quicksort using a random pivot element

c. Quicksort using a pivot as the median element (Finding pivot in linear time)

d-insertion sort

e- merge sort

Perform the following tasks: A. Write the algorithm for each technique. B. Implement the code for each technique. C. Test your implemented code using the test cases provided in the next section. D. Compare the performance with respect to the time complexity of these algorithms against each other using the empirical results obtained in the previous task by plotting charts. E. Provide a technical analysis about the time complexity of these problems by using the charts from the previous task.

Input Cases: Problem instance size (n) a) For each technique, the size of n varies as 100, 1000, 10000, 100000 For each problem instance size, distinct input values should be randomly generated using the following specifications: b) Generate distinct random values between the range of: i. 1 and 500 ii. 100 and 1000 iii. 5000 and 100000 As such, for each problem you will have 12 executions (4 problem instance size each having 3 different input value generation range)

how to perform showing Analysis:
you will plot a single multi-line chart. The ticks on the x-axis will represent each problem instance size
and y-axis will represent a count of the number of comparisons performed for each technique given a
problem instance size. The series in these line charts will represent the different sorting techniques you
have implemented. Use values generated between the range of 5000 to 100000 for each problems’
problem instance size.

Solutions

Expert Solution

A. Algorithm for all the sorting techniques:

1. Insertion Sort:

Insertion sort(array, number)

{

for (i from 1 to n, increment i by 1)

{

key = arr [i];

j = i-1;

while (j greater than 0 and array[j] > key value)

{ arr [j + 1] = arr[j];

            j = j - 1;

        }

        arr[j + 1] = key;

    }

}

2. Merge Sort:

MergeSort(arr[], l,  r)
If r > l
 1. Find the middle point to divide the array into two halves:  
         middle m = (l+r)/2
2. Call mergeSort for first half:   
             Call mergeSort(arr, l,m)
3. Call mergeSort for second half:
             Call mergeSort(arr, m+1, r)
4. Merge the two halves sorted in step 2 and 3:
             Call merge(arr, l, m, r)

3. Quick sort using pivot as maximum element:

Algorithm:

/* low  --> Starting index,  high  --> Ending index */
quickSort(arr[], low, high)
{
    if (low < high)
    {
        /* pi is partitioning index, arr[pi] is now
           at right place */
        pi = partition(arr, low, high);

        quickSort(arr, low, pi - 1);  // Before pi
        quickSort(arr, pi + 1, high); // After pi
    }
}

4. Quick sort using random pivot elements:

partition(arr[], lo, hi) 
    pivot = arr[hi]
    i = lo     // place for swapping
    for j := lo to hi – 1 do
        if arr[j] <= pivot then
            swap arr[i] with arr[j]
            i = i + 1
    swap arr[i] with arr[hi]
    return i

partition_r(arr[], lo, hi)
    r = Random Number from lo to hi
    Swap arr[r] and arr[hi]
    return partition(arr, lo, hi)

quicksort(arr[], lo, hi)
    if lo < hi
        p = partition_r(arr, lo, hi)
        quicksort(arr, p-1, hi)
        quicksort(arr, p+1, hi)

5. Quick sort using pivot as the median element:

Algorithm:

int partition(int arr[], int l, int h)

{

    int x = arr[h];

    int i = (l - 1);

    for (int j = l; j <= h - 1; j++) {

        if (arr[j] <= x) {

            i++;

            swap(&arr[i], &arr[j]);

        }

    }

    swap(&arr[i + 1], &arr[h]);

    return (i + 1);

}

B) Implement code for each technique:

1. Insertion Sort:
#include <bits/stdc++.h> 
using namespace std; 
  
/* Function to sort an array using insertion sort*/
void insertionSort(int arr[], int n)  
{  
    int i, key, j;  
    for (i = 1; i < n; i++) 
    {  
        key = arr[i];  
        j = i - 1;  
  
        /* Move elements of arr[0..i-1], that are  
        greater than key, to one position ahead  
        of their current position */
        while (j >= 0 && arr[j] > key) 
        {  
            arr[j + 1] = arr[j];  
            j = j - 1;  
        }  
        arr[j + 1] = key;  
    }  
}  
  
// A utility function to print an array of size n  
void printArray(int arr[], int n)  
{  
    int i;  
    for (i = 0; i < n; i++)  
        cout << arr[i] << " ";  
    cout << endl; 
}  
  
/* Driver code */
int main()  
{  
    int arr[] = { 12, 11, 13, 5, 6 };  
    int n = sizeof(arr) / sizeof(arr[0]);  
  
    insertionSort(arr, n);  
    printArray(arr, n);  
  
    return 0;  
}  


2. Merge sort:
#include <stdio.h> 
#include <stdlib.h> 
  
// Merges two subarrays of arr[]. 
// First subarray is arr[l..m] 
// Second subarray is arr[m+1..r] 
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[n1], R[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 */
void mergeSort(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 
        mergeSort(arr, l, m); 
        mergeSort(arr, m + 1, r); 
  
        merge(arr, l, m, r); 
    } 
} 
  
/* UTILITY FUNCTIONS */
/* Function to print an array */
void printArray(int A[], int size) 
{ 
    int i; 
    for (i = 0; i < size; i++) 
        printf("%d ", A[i]); 
    printf("\n"); 
} 
  
/* Driver program to test above functions */
int main() 
{ 
    int arr[] = { 12, 11, 13, 5, 6, 7 }; 
    int arr_size = sizeof(arr) / sizeof(arr[0]); 
  
    printf("Given array is \n"); 
    printArray(arr, arr_size); 
  
    mergeSort(arr, 0, arr_size - 1); 
  
    printf("\nSorted array is \n"); 
    printArray(arr, arr_size); 
    return 0; 
} 

3. Quick sort- pivot elements as maximum:
#include <bits/stdc++.h> 
using namespace std;  
  
// A utility function to swap two elements  
void swap(int* a, int* b)  
{  
    int t = *a;  
    *a = *b;  
    *b = t;  
}  
  
/* This 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 */
int partition (int arr[], int low, int high)  
{  
    int pivot = arr[high]; // pivot  
    int i = (low - 1); // Index of smaller element  
  
    for (int j = low; j <= high - 1; j++)  
    {  
        // If current element is smaller than the pivot  
        if (arr[j] < pivot)  
        {  
            i++; // increment index of smaller element  
            swap(&arr[i], &arr[j]);  
        }  
    }  
    swap(&arr[i + 1], &arr[high]);  
    return (i + 1);  
}  
  
/* The main function that implements QuickSort  
arr[] --> Array to be sorted,  
low --> Starting index,  
high --> Ending index */
void quickSort(int arr[], int low, int high)  
{  
    if (low < high)  
    {  
        /* pi is partitioning index, arr[p] is now  
        at right place */
        int pi = partition(arr, low, high);  
  
        // Separately sort elements before  
        // partition and after partition  
        quickSort(arr, low, pi - 1);  
        quickSort(arr, pi + 1, high);  
    }  
}  
  
/* Function to print an array */
void printArray(int arr[], int size)  
{  
    int i;  
    for (i = 0; i < size; i++)  
        cout << arr[i] << " ";  
    cout << endl;  
}  
  
// Driver Code 
int main()  
{  
    int arr[] = {10, 7, 8, 9, 1, 5};  
    int n = sizeof(arr) / sizeof(arr[0]);  
    quickSort(arr, 0, n - 1);  
    cout << "Sorted array: \n";  
    printArray(arr, n);  
    return 0;  
} 


4. Quicksort - random pivot elements:

#include <cstdlib>
#include <iostream>
using namespace std;
 
// This 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
int partition(int arr[], int low, int high)
{
    // pivot
    int pivot = arr[high]; 
   
    // Index of smaller element
    int i = (low - 1); 
 
    for (int j = low; j <= high - 1; j++) 
    {
        // If current element is smaller
        // than or equal to pivot
        if (arr[j] <= pivot) {
 
            // increment index of 
            // smaller element
            i++; 
            swap(arr[i], arr[j]);
        }
    }
    swap(arr[i + 1], arr[high]);
    return (i + 1);
}
 
// Generates Random Pivot, swaps pivot with
// end element and calls the partition function
int partition_r(int arr[], int low, int high)
{
    // Generate a random number in between
    // low .. high
    srand(time(NULL));
    int random = low + rand() % (high - low);
 
    // Swap A[random] with A[high]
    swap(arr[random], arr[high]);
 
    return partition(arr, low, high);
}
 
/* The main function that implements
QuickSort
arr[] --> Array to be sorted,
low --> Starting index,
high --> Ending index */
void quickSort(int arr[], int low, int high)
{
    if (low < high) {
 
        /* pi is partitioning index,
        arr[p] is now
        at right place */
        int pi = partition_r(arr, low, high);
 
        // Separately sort elements before
        // partition and after partition
        quickSort(arr, low, pi - 1);
        quickSort(arr, pi + 1, high);
    }
}
 
/* Function to print an array */
void printArray(int arr[], int size)
{
    int i;
    for (i = 0; i < size; i++)
        printf("%d ", arr[i]);
    printf("\n");
}
 
// Driver Code
int main()
{
    int arr[] = { 10, 7, 8, 9, 1, 5 };
    int n = sizeof(arr) / sizeof(arr[0]);
    quickSort(arr, 0, n - 1);
    printf("Sorted array: \n");
    printArray(arr, n);
    return 0;
}


5. Quick sort - median elements:

#include "bits/stdc++.h"
using namespace std;
 
// Utility function to swapping of element
void swap(int* a, int* b)
{
    int temp = *a;
    *a = *b;
    *b = temp;
}
 
// Returns the correct position of
// pivot element
int Partition(int arr[], int l, int r)
{
    int lst = arr[r], i = l, j = l;
    while (j < r) {
        if (arr[j] < lst) {
            swap(&arr[i], &arr[j]);
            i++;
        }
        j++;
    }
    swap(&arr[i], &arr[r]);
    return i;
}
 
// Picks a random pivot element between
// l and r and partitions arr[l..r]
// around the randomly picked element
// using partition()
int randomPartition(int arr[], int l,
                    int r)
{
    int n = r - l + 1;
    int pivot = rand() % n;
    swap(&arr[l + pivot], &arr[r]);
    return Partition(arr, l, r);
}
 
// Utility function to find median
void MedianUtil(int arr[], int l, int r,
                int k, int& a, int& b)
{
 
    // if l < r
    if (l <= r) {
 
        // Find the partition index
        int partitionIndex
            = randomPartition(arr, l, r);
 
        // If partion index = k, then
        // we found the median of odd
        // number element in arr[]
        if (partitionIndex == k) {
            b = arr[partitionIndex];
            if (a != -1)
                return;
        }
 
        // If index = k - 1, then we get
        // a & b as middle element of
        // arr[]
        else if (partitionIndex == k - 1) {
            a = arr[partitionIndex];
            if (b != -1)
                return;
        }
 
        // If partitionIndex >= k then
        // find the index in first half
        // of the arr[]
        if (partitionIndex >= k)
            return MedianUtil(arr, l,
                              partitionIndex - 1,
                              k, a, b);
 
        // If partitionIndex <= k then
        // find the index in second half
        // of the arr[]
        else
            return MedianUtil(arr,
                              partitionIndex + 1,
                              r, k, a, b);
    }
 
    return;
}
 
// Function to find Median
void findMedian(int arr[], int n)
{
    int ans, a = -1, b = -1;
 
    // If n is odd
    if (n % 2 == 1) {
        MedianUtil(arr, 0, n - 1,
                   n / 2, a, b);
        ans = b;
    }
 
    // If n is even
    else {
        MedianUtil(arr, 0, n - 1,
                   n / 2, a, b);
        ans = (a + b) / 2;
    }
 
    // Print the Median of arr[]
    cout << "Median = " << ans;
}
 
// Driver program to test above methods
int main()
{
    int arr[] = { 12, 3, 5, 7, 4, 19, 26 };
    int n = sizeof(arr) / sizeof(arr[0]);
    findMedian(arr, n);
    return 0;
}




 

Note: Due to inavailability of time, I was able to complete first 2 bits, kindly re upload the rest of the bits. I'll complete those by tonight.

Hope you understand.

And kindly upvote if my answer suffice the requirements.


Related Solutions

Programming Language: JAVA In this assignment you will be sorting an array of numbers using the...
Programming Language: JAVA In this assignment you will be sorting an array of numbers using the bubble sort algorithm. You must be able to sort both integers and doubles, and to do this you must overload a method. Bubble sort work by repeatedly going over the array, and when 2 numbers are found to be out of order, you swap those two numbers. This can be done by looping until there are no more swaps being made, or using a...
Choose one of the following cryptography techniques and implement it using (java )programming language. Your program...
Choose one of the following cryptography techniques and implement it using (java )programming language. Your program should provide the user with two options Encryption and Decryption, with a simple UI to get the input from the user, and view the result. You can use any restriction you need for the user input but you need to clarify that and validate the user input base on your restriction. ● Feistel ● Keyword columnar ● Any cryptosystem of your choice (needs to...
Language for this question is Java write the code for the given assignment Given an n...
Language for this question is Java write the code for the given assignment Given an n x n matrix, where every row and column is sorted in non-decreasing order. Print all elements of matrix in sorted order.Input: The first line of input contains an integer T denoting the number of test cases. Then T test cases follow. Each test case contains an integer n denoting the size of the matrix. Then the next line contains the n x n elements...
Given your expertise in language development, at this point of the semester, what techniques or behaviors...
Given your expertise in language development, at this point of the semester, what techniques or behaviors would you advise parents to use to help improve their child's language skills? What are some of the best methods to teach a child two languages?
-----xxxxx-------Could you please use java language. thank you. :::::: XXXX::::::::::: Implement a recursive reverse sorting algorithm....
-----xxxxx-------Could you please use java language. thank you. :::::: XXXX::::::::::: Implement a recursive reverse sorting algorithm. The following requirements should meet: a The program shall graphically prompt the user for a file. bThe program shall read the selected file which will contain 1 integer per line. c. The program shall sort the values it reads from the file from largest to smallest. d.The program shall write the values to an output file from largest to smallest in the same directory...
This program should be written in Java language. Given the uncertainty surrounding the outbreak of the...
This program should be written in Java language. Given the uncertainty surrounding the outbreak of the Coronavirus disease (COVID-19) pandemic, our federal government has to work tirelessly to ensure the distribution of needed resources such as medical essentials, water, food supply among the states, townships, and counties in the time of crisis. You are a software engineer from the Right Resource, a company that delivers logistic solutions to local and state entities (schools, institutions, government offices, etc). You are working...
IN JAVA. Which sorting does in place sorting? Which sort does the minimum swap to order...
IN JAVA. Which sorting does in place sorting? Which sort does the minimum swap to order ascending /desendinf manner?
Answer the following in Java programming language Create a Java Program that will import a file...
Answer the following in Java programming language Create a Java Program that will import a file of contacts (contacts.txt) into a database (Just their first name and 10-digit phone number). The database should use the following class to represent each entry: public class contact {    String firstName;    String phoneNum; } Furthermore, your program should have two classes. (1) DatabaseDirectory.java:    This class should declare ArrayList as a private datafield to store objects into the database (theDatabase) with the...
Please use Java language in an easy way with comments! Thanks! Create a calculator that uses...
Please use Java language in an easy way with comments! Thanks! Create a calculator that uses an array of buttons for numbers from 0-9, the . for decimals, and for operators +, -, * ,/ and = as well as a JTextfield that displays the current value or the result. Use ActionListeners and LayoutManagers appropriately. The example below shows how to determine which button has been clicked. ActionListener actionListener = new ActionListener() { public void actionPerformed(ActionEvent actionEvent) { System.out.println(actionEvent.getActionCommand()); }...
Please use Java You have to write a programing for the following sorting algorithms in increasing...
Please use Java You have to write a programing for the following sorting algorithms in increasing order and print required steps in order to explain how your sorting algorithms work. 3. Implement the merge sort algorithm. With answers in this link (https://www.chegg.com/homework-help/questions-and-answers/write-programing-following-sorting-algorithms-increasing-order-print-required-steps-order--q53916147?trackid=PJ_TOK85), answer the above questions.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT