CSCI A202 - Introduction to Programming (II)

Lecture 17: Recursion, Sorting and Searching

We will look at:

We will examine recursive and non-recursive solutions to these problems.

Here's code for a Processor that carries a local storage with it (like your Vectors, except of ints) and is able to sort it using two different methods.

Bubble sort is used in both cases, but in different ways.

import java.util.*; 
 
class Processor {
  int[] storage; 
  Processor(int n) {
    storage = new int[n]; 
    for (int i = 0; i < storage.length; i++) {
      storage[i] = (int)(Math.random()*10) + 1; 
    } 
  } 
  void show() {
    for (int i = 0; i < storage.length; i++) {
      System.out.print(storage[i] + " "); 
    } 
    System.out.println(); 
  } 
  void bubbleSort() {
    int aux; 
    boolean sorted; 
    do { 
      sorted = true; 
      for (int i = 0; i < storage.length - 1; i++) {
        if (storage[i] < storage[i+1]) { 
          aux = storage[i];
          storage[i] = storage[i+1];
          storage[i+1] = aux; 
          sorted = false; 
        } 
      } 
    } while (! sorted); 
  } 
  boolean recursiveSort() {
    int aux; 
    boolean sorted = true; 
    for (int i = 0; i < storage.length - 1; i++) {
      if (storage[i] < storage[i+1]) {
        aux = storage[i]; 
        storage[i] = storage[i+1]; 
        storage[i+1] = aux; 
        sorted = false; 
      } 
    } 
    return sorted || recursiveSort(); // there it is... 
  } 
  public static void main(String[] args) {
    Date start, stop; 
    Processor b = new Processor(10); 
    b.show(); 
    start = new Date();
    // b.bubbleSort();  
    b.recursiveSort(); 
    stop  = new Date(); 
    b.show(); 
    System.out.println("Time elapsed: " +
        (stop.getTime() - start.getTime()) + " milliseconds"); 
  } 
}