繁体   English   中英

如果没有变化,如何减少循环次数?

[英]How to reduce the number of loops if there is no change?

此代码是 Java 中的基数排序。

现在我可以排序了。 但是如果数组没有变化,我想减少它的功能,让它停止循环显示值

我必须在哪里修复它? 请指导我,提前谢谢。

public class RadixSort {

    void countingSort(int inputArray[], int size, int place) {
        //find largest element in input array at 'place'(unit,ten's etc)
        int k = ((inputArray[0] / place) % 10);
        for (int i = 1; i < size; i++) {
            if (k < ((inputArray[i] / place) % 10)) {
                k = ((inputArray[i] / place) % 10);
            }
        }
        //initialize the count array of size (k+1) with all elements as 0.
        int count[] = new int[k + 1];
        for (int i = 0; i <= k; i++) {
            count[i] = 0;
        }
        //Count the occurrence of each element of input array based on place value
        //store the count at place value in count array.
        for (int i = 0; i < size; i++) {
            count[((inputArray[i] / place) % 10)]++;
        }
        //find cumulative(increased) sum in count array
        for (int i = 1; i < (k + 1); i++) {
            count[i] += count[i - 1];
        }
        //Store the elements from input array to output array using count array.
        int outputArray[] = new int[size];
        for (int j = (size - 1); j >= 0; j--) {
            outputArray[count[((inputArray[j] / place) % 10)] - 1] = inputArray[j];
            count[(inputArray[j] / place) % 10]--;//decrease count by one.
        }
        for (int i = 0; i < size; i++) {
            inputArray[i] = outputArray[i];//copying output array to input array.
        }
        System.out.println(Arrays.toString(inputArray));
    }

    void radixSort(int inputArray[], int size) {
        //find max element of inputArray
        int max = inputArray[0];
        for (int i = 1; i < size; i++) {
            if (max < inputArray[i]) {
                max = inputArray[i];
            }
        }
        //find number of digits in max element
        int d = 0;
        while (max > 0) {
            d++;
            max /= 10;
        }
        //Use counting cort d no of times
        int place = 1;//unit place
        for (int i = 0; i < d; i++) {
            System.out.print("iteration no = "+(i+1)+" ");
            countingSort(inputArray, size, place);
            place *= 10;//ten's , hundred's place etc
        }
    }

1

我将拒绝为您输入一些代码,而是在概念上使用 go,因为这看起来像是家庭作业。

如果我对您的理解正确,您的问题归结为:“我想检查两个 arrays 是否相等,如果相等,则跳出循环”。 让我们先解决后半部分。 在Java中,可以使用关键字"

break;

打破一个循环。

检查两个 arrays 在 java 中是否等效的指南可在此处找到: https://www.geeks-array-javas.org/compare-two-two

抱歉,如果这不能回答您的问题。 我只是要建议一种更快的方法来查找每个元素的数字。 取元素的以 10 为底的对数并加 1。
像这样: int digits = (int) Math.log10(i)+1;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM