问题描述:

so when I go to compile this Eclipse says, that the numbers for Insertionct and Shakerct are 0 and prints out a tie. I know for a fact that both methods are sorting correctly, but for some reason it doesn't return the amount of comparisons that they are making to main in order to decide which one sorted the array faster. Thanks for any help in advance.

import java.io.*;

import java.util.*;

public class Sorts {

private static Scanner in;

public static void main(String[] args) throws Exception {

in = new Scanner(System.in);

System.out.print("How many strings will you be entering? ");

int sz = Integer.parseInt (in.nextLine());

String[] A = new String[sz];

String[] B = new String[sz];

for (int i = 0; i < sz; i++){

System.out.print ("Enter String #"+(i+1)+": ");

A[i] = in.nextLine();// sets the array at i equal to a string

B[i] = A[i]; // sets array B to the same as array A so I can use it in the shaker sort method

}

int Insertionct = 0;

int Shakerct = 0;

System.out.println(Insertionct);

System.out.println(Shakerct);

if (Shakerct > Insertionct) {

System.out.println("Insertion Sort was faster!");

} else if (Shakerct < Insertionct) {

System.out.println("Shaker Sort was faster!");

} else {

System.out.println("It was a tie");

}

}

public static int InsertionSort (int Insertionct, String[] A) throws Exception { //sorts the array of strings with the insertion sort.

// initializes the count variable

int sz = A.length; // sets size equal toe array A

for (int i = 0; i < sz-1; i++)

for (int j = i; j >= 0 && A[j].compareTo (A[j+1]) > 0; j--) {

Insertionct++;

String t = A[j]; //switch A[j], A[j+1]

A[j] = A[j+1];

A[j+1] = t;

}

return Insertionct;

}

public static int ShakerSort (int Shakerct, String[] B) throws Exception {//Uses the ShakerSort in order to order the array.

int sz = B.length;

for (int i = 0; i < sz; i++){

int nsct = 0;

for(int j = nsct+sz-1; j > i; j--){//runs through the array backwards and then swaps if it needs to

Shakerct++;

if (B[j].compareTo(B[j-1]) < 0) {

nsct = 0;

String t = B[j];

B[j] = B[j-1];

B[j-1] = t;

} else {

nsct++; // if no swap happens it increases no swap to increment the starting points.

}

}

for (int j = nsct; j > sz-i-1; j++){

if (B[j].compareTo(B[j+1]) > 0){//runs through the array going forward swaps if needed

Shakerct++;

nsct = 0;

String t = B[j];

B[j] = B[j+1];

B[j+1] = t;

} else {

nsct++;// increases no-swap count if no swap happens and changes the starting point.

}

}

}

return Shakerct;

}

}

网友答案:

You don't call InsertionSort and ShakerSort in main.

相关阅读:
Top