java中的单个程序中多个排序方法失败

时间:2018-06-12 23:39:40

标签: java sorting

我的程序没有显示正在排序的每个正确列表,比较数和除了气泡排序方法之外的分配数。我想我错过了重置输入字符串但无法找出重置输入的方法。 有没有办法在不同的排序方法中对一个输入进行排序。 这是我的代码:

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.Scanner;

/**
 * Create a program that does head-to-head comparisons between four sorting
 * methods: improved bubble sort; selection sort; insertion sort; and Shell
 * sort.
 *
 */
public class SortAlgorithms {

private static char tracing;
private static char list;

private static int numAsgn = 0;
private static int numComp = 0;

private static int size;
private static int min;
private static int max;
private static final Scanner KBD = new Scanner(System.in);

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

    BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

    System.out.print("How many elements do you want in the list? ");
    size = KBD.nextInt();
    System.out.print("What are the smallest and largest values for lsit elements? ");
    min = KBD.nextInt();
    max = KBD.nextInt();

    KBD.nextLine();
    pause();

    System.out.print("Would you like to see the list before it's sorted? ");
    list = Character.toUpperCase(br.readLine().charAt(0));

    System.out.print("Would you like to see the list as it's being sorted? ");
    tracing = Character.toUpperCase(br.readLine().charAt(0));
    pause();

            sortNumbers();
}


// prompt the user and wait for them to press enter
private static void pause() {
    System.out.print("\n...Press enter...");
    KBD.nextLine();
    System.out.println();
}


  /**
 * Sort a list of integer values, generated randomly.
 */
public static void sortNumbers() {
    resetCounts();

    Integer[] numbers = randomNumbers(size, min, max);
    if (list == 'Y') {
        System.out.println("Here is the list: " + Arrays.toString(numbers));
        pause();
    }

    System.out.printf("\n%1s%25s%20s%20s\n", "Method", "#COMP", "#ASGN", "#OPS");

    bubbleSort(numbers);
    System.out.printf("%1s%25d%20d%20d\n", "Bubble", numComp, numAsgn, numAsgn + numComp);

    selectionSort(numbers);
    System.out.printf("%1s%22d%20d%20d\n", "Selection", numComp, numAsgn, numAsgn + numComp);

    insertionSort(numbers);
    System.out.printf("%1s%22d%20d%20d\n", "Insertion", numComp, numAsgn, numAsgn + numComp);

    shellSort(numbers);
    System.out.printf("%1s%26d%20d%20d\n", "Shell", numComp, numAsgn, numAsgn + numComp);
}

/**
 * Reset the operation counts to zero.
 */
public static void resetCounts() {
    numAsgn = 0;
    numComp = 0;
}

/**
 * Generate an array of random values.
 *
 * @param howMany the length of the list to be generated.
 * @param lo the smallest value allowed in the list
 * @param hi the largest value allowed in the list
 */
public static Integer[] randomNumbers(int size, int min, int max) {
    int range = max - min + 1;
    Integer[] result = new Integer[size];
    for (int i = 0; i < size; ++i) {
        result[i] = (int) (min + range * Math.random());
    }
    return result;
}

/**
 * Perform bubble sort on the given array.
 *
 * @param a the array to sort.
 */
public static <T extends Comparable<? super T>>
        void bubbleSort(T[] a) {
    for (int i = a.length - 1; i > 0; --i) {
        boolean elementSwapped = false;
        //numComp++;
        for (int j = 0; j < i; ++j) {
            numComp++;
            if (a[j].compareTo(a[j + 1]) > 0) {
                numAsgn += 3;
                T temp = a[j + 1];
                a[j + 1] = a[j];
                a[j] = temp;
                elementSwapped = true;
            }
        }
        if (!elementSwapped) {
            break;
        }
        //if (tracing == 'Y') {
            System.out.println("one more bubbled up: "
                    + Arrays.toString(a));
        //}

    }
}

/**
 * Perform insertion sort on the given array.
 *
 * @param a the array to sort.
 */
public static <T extends Comparable<? super T>>
        void insertionSort(T[] a) {
    for (int i = 0; i < a.length - 1; ++i) {
        int p = i + 1;
        T temp = a[p];
        ++numAsgn;
        while (p > 0 && a[p - 1].compareTo(temp) > 0) {
            ++numComp;
            a[p] = a[p - 1];
            ++numAsgn;
            --p;
        }
        if (p > 0) {
            ++numComp; // count the last a[p-1] comparison
        }
        a[p] = temp;
        ++numAsgn;
        //if (tracing == 'Y') {
            System.out.println("one more inserted: " + Arrays.toString(a));
        //}
    }

}

/**
 * Perform selection sort on the given array. if tracing, show the array
 * after each selection round.
 *
 * @param a the array to sort
 */
public static <T extends Comparable<? super T>>
        void selectionSort(T[] a) {
    for (int i = 0; i < a.length - 1; ++i) {
        int p = i;
        ++numAsgn;
        for (int j = i + 1; j < a.length; ++j) {
            ++numComp;
            if (a[j].compareTo(a[p]) < 0) {
                p = j;
                ++numAsgn;
            }
        }
            T temp = a[i];
            a[i] = a[p];
            a[p] = temp;
            ++numAsgn;

        //if (tracing == 'Y') {
            System.out.println("one more selected: " + Arrays.toString(a));
        //}
    }
}

/**
 * Perform shell sort on the given array.
 *
 * @param a the array to sort.
 */
public static <T extends Comparable<? super T>>
        void shellSort(T[] a) {
    int gap = a.length / 2;
    ++numComp;
    while (gap >= 1) {

        if (gap % 2 == 0) {
            ++gap;
        }
        ++numComp;
        for (int i = gap; i < a.length; ++i) {
            ++numAsgn;
            int p = i;
            T temp = a[p];
            ++numComp;
            while (p >= gap && a[p - gap].compareTo(temp) > 0) {
                a[p] = a[p - gap];
                p -= gap;
                ++numAsgn;
            }
            a[p] = temp;
            ++numAsgn;
        }
        //if (tracing == 'Y') {
            System.out.println("...gap=" + gap + ": " + Arrays.toString(a));
       // }
        gap /= 2;

    }
}

/**
 * Calculate how many operations a list of the given length should take.
 *
 * @param numItems the number of elements in a list.
 * @return the number of operations expected (on average) to sort that list
 */
private static int expect(int numItems) {
    return (numItems * numItems + numItems) * 5 / 4;
}

}

1 个答案:

答案 0 :(得分:1)

每次排序时,您都会覆盖数组numbers,因此bubbleSort是第一个排序方法,您只能看到它。每个连续的排序方法只对排序的数组进行操作。此外,由于您已将计数定义为成员变量,因此需要在每个方法之前调用resetCounts()以获得新计数。在将数组传递给每个排序方法之前复制数组,并重置计数应该解决这个问题。

System.out.printf("\n%1s%25s%20s%20s\n", "Method", "#COMP", "#ASGN", "#OPS");

resetCounts();
bubbleSort(Arrays.copyOf(numbers, numbers.length));
System.out.printf("%1s%25d%20d%20d\n", "Bubble", numComp, numAsgn, numAsgn + numComp);

resetCounts();
selectionSort(Arrays.copyOf(numbers, numbers.length));
System.out.printf("%1s%22d%20d%20d\n", "Selection", numComp, numAsgn, numAsgn + numComp);

resetCounts();
insertionSort(Arrays.copyOf(numbers, numbers.length));
System.out.printf("%1s%22d%20d%20d\n", "Insertion", numComp, numAsgn, numAsgn + numComp);

resetCounts();
shellSort(numbers);
System.out.printf("%1s%26d%20d%20d\n", "Shell", numComp, numAsgn, numAsgn + numComp);