Question

In: Computer Science

Can someone fix this code so that it can count comparison and exchange? import java.util.Arrays; class...

Can someone fix this code so that it can count comparison and exchange?

import java.util.Arrays;

class Main
{
static int comparisons;
static int exchanges;

// Recursive function to perform insertion sort on sub-array arr[i..n]
public static void insertionSort(int[] arr, int i, int n)
{
int value = arr[i];
int j = i;

// Find index j within the sorted subset arr[0..i-1]
// where element arr[i] belongs
while (j > 0 && arr[j - 1] > value)
{
arr[j] = arr[j - 1];
j--;
}
  
arr[j] = value;

// Note that subarray arr[j..i-1] is shifted to
// the right by one position i.e. arr[j+1..i]

if (i + 1 <= n) {
insertionSort(arr, i + 1, n);
}
  
}

public static void main(String[] args)
{
int[] arr = { 3, 8, 5, 4, 1, 9, -2 };

// Start from second element (element at index 0
// is already sorted)
insertionSort(arr, 1, arr.length - 1);

// print the sorted array

System.out.println("comparisons: " + comparisons);
System.out.println("exchanges: " + exchanges);

System.out.println(Arrays.toString(arr));
}

Solutions

Expert Solution

Updated Program:

import java.util.Arrays;

class Main
{
    static int comparisons;
    static int exchanges;
    
    // Recursive function to perform insertion sort on sub-array arr[i..n]
    public static void insertionSort(int[] arr, int i, int n)
    {
        int value = arr[i];
        int j = i;
        
        // Find index j within the sorted subset arr[0..i-1]
        // where element arr[i] belongs
        while (j > 0 && arr[j - 1] > value)
        {
            comparisons++;
            arr[j] = arr[j - 1];
            j--;
        }
          
        arr[j] = value;
        
        // Note that subarray arr[j..i-1] is shifted to
        // the right by one position i.e. arr[j+1..i]
        exchanges++;
        if (i + 1 <= n) {
            insertionSort(arr, i + 1, n);
        }
      
    }
    
    public static void main(String[] args)
    {
        int[] arr = { 3, 8, 5, 4, 1, 9, -2 };
        
        // Start from second element (element at index 0
        // is already sorted)
        insertionSort(arr, 1, arr.length - 1);
        
        // print the sorted array
        
        System.out.println("comparisons: " + comparisons);
        System.out.println("exchanges: " + exchanges);
        
        System.out.println(Arrays.toString(arr));
    }
}

Output:

Thumbs Up Please !!!


Related Solutions

I wrote this code and it produces a typeError, so please can you fix it? import...
I wrote this code and it produces a typeError, so please can you fix it? import random def first_to_a_word(): print("###### First to a Word ######") print("Instructions:") print("You will take turns choosing letters one at a time until a word is formed.") print("After each letter is chosen you will have a chance to confirm whether or not a word has been formed.") print("When a word is formed, the player who played the last letter wins!") print("One of you has been chosen...
Can someone please convert this java code to C code? import java.util.LinkedList; import java.util.List; public class...
Can someone please convert this java code to C code? import java.util.LinkedList; import java.util.List; public class Phase1 { /* Translates the MAL instruction to 1-3 TAL instructions * and returns the TAL instructions in a list * * mals: input program as a list of Instruction objects * * returns a list of TAL instructions (should be same size or longer than input list) */ public static List<Instruction> temp = new LinkedList<>(); public static List<Instruction> mal_to_tal(List<Instruction> mals) { for (int...
Can you fix the errors in this code? import java.util.Scanner; public class Errors6 {    public...
Can you fix the errors in this code? import java.util.Scanner; public class Errors6 {    public static void main(String[] args) {        System.out.println("This program will ask the user for three sets of two numbers and will calculate the average of each set.");        Scanner input = new Scanner(System.in);        int n1, n2;        System.out.print("Please enter the first number: ");        n1 = input.nextInt();        System.out.print("Please enter the second number: ");        n2 =...
Can you fix the errors in this code? package demo; /** * * */ import java.util.Scanner;...
Can you fix the errors in this code? package demo; /** * * */ import java.util.Scanner; public class Booolean0p {        public class BooleanOp {            public static void main(String[] args) {                int a = 0, b = 0 , c = 0;                Scanner kbd = new Scanner(System.in);                System.out.print("Input the first number: ");                a = kbd.nextInt();                System.out.print("Input...
----fix code to search and delete a student by Identification number import java.util.Scanner; public class COurseCom666...
----fix code to search and delete a student by Identification number import java.util.Scanner; public class COurseCom666 {     private String courseName;     private String[] students = new String[1];     private int numberOfStudents;     public COurseCom666(String courseName) {         this.courseName = courseName;     }     public String[] getStudents() {         return students;     }     public int getNumberOfStudents() {         return numberOfStudents;     }     public String getCourseName() {         return courseName;     }     public int DeleteStudentsByID() {         return...
Can someone fix solver class. it suppose to call method from sort class for insertion and...
Can someone fix solver class. it suppose to call method from sort class for insertion and heap sort. However its not giving the outuput.. Run following class Solver where 20 array instances of 1M random integers are sorted using Insertion- sort and Heap-sort, respectively public class Solver {    public static void main(String[] args) { final int SIZE = 1000000; // 1 million final int Instances=20; int[][] TwoDimArray = new int[Instances][SIZE];    Sort s = new Sort();    for(int i=0;...
can you please look at the following code and fix it for me so that it...
can you please look at the following code and fix it for me so that it does not have any syntax errors. also can you tell me what was fixed /** * Driver program to demonstrate calling methods of Client class. * * @author Doyt Perry/Tina Comston * @version Fall 2019 */ public class ClientDemo { public static void main() { /** * main method - makes this an executable program. */ // create a client with placeholder values System.out.println("Client...
Can you please rewrite this Java code so it can be better understood. import java.util.HashMap; import...
Can you please rewrite this Java code so it can be better understood. import java.util.HashMap; import java.util.Scanner; import java.util.Map.Entry; public class Shopping_cart {       static Scanner s= new Scanner (System.in);    //   declare hashmap in which key is dates as per mentioned and Values class as value which consists all the record of cases    static HashMap<String,Item> map= new HashMap<>();    public static void main(String[] args) {        // TODO Auto-generated method stub        getupdates();    }...
fix this code in python and show me the output. do not change the code import...
fix this code in python and show me the output. do not change the code import random #variables and constants MAX_ROLLS = 5 MAX_DICE_VAL = 6 #declare a list of roll types ROLLS_TYPES = [ "Junk" , "Pair" , "3 of a kind" , "5 of a kind" ] #set this to the value MAX_ROLLS pdice = [0,0,0,0,0] cdice = [0,0,0,0,0] #set this to the value MAX_DICE_VAL pdice = [0,0,0,0,0,0] cdice = [0,0,0,0,0,0] #INPUT - get the dice rolls i...
can someone change this code so that timestandard can be calculated at the end of the...
can someone change this code so that timestandard can be calculated at the end of the code using the inputs n,RF,PFD, and the measured cycles, instead of being called from the beginning of the code using namespace std; float timestandard(float time, float rf, float pfd) { return((time / 100) * rf * (1 + pfd)); /* calculating the time standard using the given formula*/ } int main() { int n, rf, pfd, x; /* inputs are taken*/ cout << "****...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT