/* Low-Level Sorting Example
   H. Conrad Cunningham
   Version #1:  29 March 2010
   Version #1a: 30 March 2010 Error corrections

   This is relatively straightforward Scala translation of the C++
   example from section 21.1.1 of Timothy Budd's _An Introduction to
   Object-Oriented Programming_, Third Edition.

123456789012345678901234567890123456789012345678901234567890123456789012345678

*/

// Employee records (use Scala case class for convenience)
case class Employee(name: String, salary: Int, startingYear: Int) 


object SortEmployee {

  // Method to sort first n element of an array of Employees by startingYear
  def sort(data: Array[Employee], n: Int) {
    for (i <- 1 to n-1) {      
      var j = i - 1
      while (j >= 0 && data(j+1).startingYear < data(j).startingYear) {
        val temp  = data(j) 
        data(j)   = data(j+1)
        data(j+1) = temp
        j = j - 1
      }
    }
  }

  // Do some testing
  def main(args: Array[String]) {
    val data = Array(Employee("Two",  10, 2007), 
                     Employee("One",   9, 2006), 
                     Employee("Three", 8, 2008), 
                     Employee("Zero", 12, 2005) )
    println("Unsorted data:  " + data.toList.mkString(", ") )    
    sort(data,data.length)
    println("Sorted data:    " + data.toList.mkString(", ") ) 
 }

}
