Difficulty solving problem 23 bubble in array

Back to Problem Solutions forum

guntherrose     2015-08-13 21:57:46

Hello, I am having some trouble solving the bubble in array problem. I used the code which correctly solved the previous problems, 17 array checksum and 27 bubble sort, but I cannot get the same code to give correct answers. The swaps as well as the checksum value come out incorrect every time.

The code for checksum portion:

    public static long checksum(ArrayList<Long> values){
        int seed = 113;
        int limit = 10000007;
        int len = values.size();
        long result = 0;
        for(int i = 0; i < len; i++){
            long n = values.get(i);
            result = ((n + result) * seed)%limit;
        }
        return (result);
    }

The code for bubble sort:

    boolean swapped = true;
    int passes = 0;
    while(swapped){
        swapped = false;
        for(int i = 0; i < values.size()-1; i++){

            if(values.get(i) > values.get(i+1)){
                long temp = values.get(i);
                values.set(i, values.get(i+1));
                values.set(i+1, temp);
                swapped = true;
                swaps++;
            }    

        }
        passes++;
    }

Please point me in the right direction for what I'm doing wrong. While I wait, I will solve a different problem.

MontBlanc     2015-08-13 22:36:29

Hello,
In 'bubble in array' you have to browse through the line only once, and do the necessary swaps.
In 'bubble sort' you browse the line as many times as necessary until it is perfectly sorted and won't budge (as it should).

Hope it helps.

guntherrose     2015-08-13 23:21:47

Thank you for the clarification, that solved the problem.

Gxz-NGU     2018-06-14 03:13:51

emmm,I want to delete my review.

Please login and solve 5 problems to be able to post at forum