Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

I need an insertion sort and selection sort Java code to count comparisons and s

ID: 675552 • Letter: I

Question

I need an insertion sort and selection sort Java code to count comparisons and swaps in an array... I have one but it only counts swaps:

public static int counter(int array[], int n){

               int swap = 0;

          

                   for (int i = 1; i < n; i++){

                   int j = i;

                   int B = array[i];

                   while ((j > 0) && (array[j-1] > B)){

                   swap++;

                   ;

                   array[j] = array[j-1];

                   j--;

                   }

                   array[j] = B;

                   }

                   return swap;

              

                   }

Explanation / Answer

public static int numOfComps = 0, numOfSwaps = 0; public static void insertionSort(int[] array) { int unsortedValue; // The first unsorted value int scan; // Used to scan the array // The outer loop steps the index variable through // each subscript in the array, starting at 1. The portion of // the array containing element 0 by itself is already sorted. for (int index = 1; index 0 && array[scan-1] > unsortedValue) { array[scan] = array[scan - 1]; scan--; // Counts the number of values swaps numOfSwaps ++; } // Insert the unsorted value in its proper position // within the sorted subset. array[scan] = unsortedValue; // Counts the number of values comparisons numOfComps ++; } System.out.println(" Number of comps = " + numOfComps); System.out.println("Number of swaps = " + numOfSwaps); } } public String selectionSort(int[] numbers) { System.out.println("******|Selection Sort|******"); StringBuilder originalArray = new StringBuilder(); int comparisons = 0; int swaps = 0; for(int i = 0; i 0; x--) { first = 0; comparisons++; for(int y = 1; y numbers[first]) { first = y; //comparisons++; swaps++; } temp = numbers[first]; numbers[first] = numbers[x]; numbers[x] = temp; //swaps++; } } //Create a StringBuilder object - to hold //the output of sorted numbers. StringBuilder sb = new StringBuilder(); //Loop through the now sorted array - appending //each subsequent number in the array to the //StringBuilder object. for(int i = 0; i
Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote