RHS   Allan   SW construction Exercises WhatHappens?


 

What Happens ?

Describe what the following code does:

public int[] X( int[] list ) {
  if (list != null) {
    if (list.length > 1) {
      for (int i = 0; i < list.length; i++) {
        for (int j = list.length - 1; j > i; j--) {
          if (list [j] < list[i]) {
            swap(list, i, j);
          }
        }
      }
      return list;
    } else {
      return list;
    }
  } else {
    return null;
  }
}

//switches two elements in a list
private void swap(int[] list, int idx1, int idx2) {
  int temp = list[idx1];
  list[idx1] = list[idx2];
  list[idx2] = temp;
}

Hint: Use pen and paper. Define an int-array with 3 or 4 int-values and "run" the code on the paper using this array.


Maintained by: Allan Helboe Nielsen
Updated: 3 November, 2005 1:04