#!/usr/bin/guile \ -e main -s !# ;;; Copyright 2005 Daniel Cer (daniel.cer@cs.colorado.edu) ;;; ;;; This work is licensed under the Creative Commons Attribution-NonCommercial- ;;; ShareAlike License. To view a copy of this license, visit ;;; http://creativecommons.org/licenses/by-nc-sa/2.5/ or send a letter to ;;; Creative Commons, 543 Howard Street, 5th Floor, San Francisco, California, ;;; 94105, USA. ;; routine to read in entries from an input-port (define (read-entries input-port) (let ((in-line (read-line input-port))) (if (eof-object? in-line) '() (append (list (string->number in-line)) (read-entries input-port))))) ;; routine to find the minimum entry in a vector that has an index that is ;; greater than or equal to start-idx (define (find-min entries start-idx) (do ((idx (+ start-idx 1) (+ idx 1)) (min-idx start-idx (if (< (vector-ref entries idx) (vector-ref entries min-idx)) idx min-idx))) ((equal? idx (vector-length entries)) min-idx) '() )) ;; performs a selection sort on a vector of items (define (selection-sort entries) (do ((idx 0 (+ idx 1))) ((equal? idx (vector-length entries)) entries) (let* ((min-idx (find-min entries idx)) ; find the minimum vector val (min-val (vector-ref entries min-idx))) ; with an index >= idx (vector-set! entries min-idx (vector-ref entries idx)) ; swap idx-th entry (vector-set! entries idx min-val)))) ; with min-idx entry (define (main args) (if (not (equal? (length args) 2)) (display (string-append "Usage:\n\t" (car args) " (file with numbers to sort)\n")) (map (lambda (x) (display x) (newline)) ; display the sorted entries (vector->list (selection-sort ; perform the selection sort (list->vector (call-with-input-file (car (cdr args)) read-entries))))))) ; read in the entries