【问题标题】:Multiple sorting methods failed in single program in javajava中单个程序中的多种排序方法失败
【发布时间】:2018-06-13 08:00:16
【问题描述】:

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

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;
}

}

【问题讨论】:

    标签: java sorting


    【解决方案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);
    

    【讨论】:

    • 谢谢,我已经重置了 numAsgn 和 numComp 的计数器,但它没有给出正确的结果。你能找到错误吗?
    • @K.Ji 您对nubAsgn 的计数对我来说看起来不错,但是在您拥有(p &gt; 0 &amp;&amp; a[p - 1].compareTo(temp) &gt; 0) 的某些方法中,numComp 是一种比较,即++numComp ,不知道要不要算2,numComp += 2。除此之外,它对我来说看起来不错。
    • @K.Ji 你打赌。很高兴我能帮上忙!
    猜你喜欢
    • 2014-03-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-10-05
    • 2023-03-23
    • 1970-01-01
    相关资源
    最近更新 更多