2
public class Test{
   public static void main(String[] args){
      int[] a = {3, 2, 5, 21}; // created an array with 4 elements
      int b,c;

      for (b=0; b<=2; b++)//for loop that will have 3 iterations  
      {
        if (a[b] < a[b+1])
        {
           c=a[b];//this
           a[b] = a[b+1];//is 
           a[b+1] = c;//swapping
        }
      }

      for(b=0; b<4; b++)
      {
        System.out.println(a[b]);
      }
   }
}

This outputs :

3
5
21
2

What I got when I was writing it down:

3
5
21
21

Could someone tell me how to approach it in my thoughts?

4

4 回答 4

3

Well if you really want to just trace out the program you could go through each iteration of that first for-loop by hand (the second loop just prints the contents of a).

Before the loop starts, a holds

{3, 2, 5, 21}

First iteration (b = 0):
a[0] is not less than a[1] so we do nothing.


Second iteration (b = 1):
a[1] is less than a[2], so we swap them. Now a holds

{3, 5, 2, 21}

Third iteration (b = 2):
a[2] is less than a[3], so we swap them. Now a holds

{3, 5, 21, 2}

which is what gets printed subsequently.

于 2012-11-07T00:21:50.310 回答
1

Well, the code always outputs the initial elements of a, possibly permuted. Thus your expectation can't possibly have been correct, since it lost 2 and made 21 appear twice.

于 2012-11-07T00:18:12.170 回答
1

Well you got lost at the 3rd iteration so I'll start there.

The array is {3, 5, 2, 21}. b = 2

if (a[b] < a[b+1]) is equivalent to if (2 < 21), this is true, so...

c=a[b];//this -> c = 2

a[b] = a[b+1];//is -> a[2] = 21

a[b+1] = c;//swapping -> a[2+1] = 2

so now a[2] = 21 and a[3] = 2 and the final array is:

{3, 5, 21, 2}

于 2012-11-07T00:20:15.090 回答
0

Each time you run the full outer loop you will end up with the next smallest element at the end of the array. So as you're only running the loop once you end up with 2 (being the first smallest element) at the end of the array.

As others have mentioned, if you want to make this a complete sort then you need more iterations of the main loop to complete the sort (n-1, where n is the length of the array, so in this case you would need to run the loop 3 times).

于 2012-11-07T00:24:07.707 回答