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

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 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 << "****...
Please fix all of the errors in this Python Code. import math """ A collection of...
Please fix all of the errors in this Python Code. import math """ A collection of methods for dealing with triangles specified by the length of three sides (a, b, c) If the sides cannot form a triangle,then return None for the value """ ## @TODO - add the errlog method and use wolf fencing to identify the errors in this code def validate_triangle(sides): """ This method should return True if and only if the sides form a valid triangle...
Python programming: can someone please fix my code to get it to work correctly? The program...
Python programming: can someone please fix my code to get it to work correctly? The program should print "car already started" if you try to start the car twice. And, should print "Car is already stopped" if you try to stop the car twice. Please add comments to explain why my code isn't working. Thanks! # Program goals: # To simulate a car game. Focus is to build the engine for this game. # When we run the program, it...
Python 3 Fix the code so i can make the window larger or smaller and the...
Python 3 Fix the code so i can make the window larger or smaller and the fields adjusts everytime according to the window size import tkinter as tk from tkcalendar import DateEntry from openpyxl import load_workbook window = tk.Tk() window.title("daily logs") # window.resizable(0,0) # labels tk.Label(window, text="Bar code").grid(row=0, sticky="W", pady=20, padx=20) tk.Label(window, text="Products failed").grid(row=1, sticky="W", pady=20, padx=20) tk.Label(window, text="Money Lost").grid(row=2, sticky="W", pady=20, padx=20) tk.Label(window, text="sold by").grid(row=3, sticky="W", pady=20, padx=20) tk.Label(window, text="Failed date").grid(row=4, sticky="W", pady=20, padx=20) # entries barcode = tk.Entry(window)...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT