home *** CD-ROM | disk | FTP | other *** search
- Newsgroups: comp.lang.lisp
- Path: sparky!uunet!usc!zaphod.mps.ohio-state.edu!news.acns.nwu.edu!news.ils.nwu.edu!anaxagoras!krulwich
- From: krulwich@zowie.ils.nwu.edu (Bruce Krulwich)
- Subject: Re: sorting arrays
- In-Reply-To: lewocz@acsu.buffalo.edu's message of 30 Dec 92 00:00:11 GMT
- Message-ID: <KRULWICH.92Dec30130915@zowie.ils.nwu.edu>
- Sender: usenet@ils.nwu.edu (Mr. usenet)
- Nntp-Posting-Host: zowie.ils.nwu.edu
- Organization: The Institute for the Learning Sciences, Evanston, IL
- References: <C01pCC.MFK@acsu.buffalo.edu>
- Date: Wed, 30 Dec 1992 19:09:15 GMT
- Lines: 43
-
-
- lewocz@acsu.buffalo.edu (John S. Lewocz) writes:
-
- > What would be the most effiecient way to sort a two-dimensional
- > array using an arbitrary column as a key?
-
- I think that the following solution is pretty efficient, since it doesn't
- require copying row data during the sort, or creating loads of new arrays.
-
- It works by sorting a seperate vector that contains numbers of rows of the
- original array. This way the SORT function just sorts an integer vector,
- which should be pretty quick, using a KEY that maps onto the array being
- sorted. Then we just copy the data into the appropriate rows of a new array.
- Consing is limited to making one vector the side of the row-dimension of the
- original array, and then making a new array to return.
-
- ** Note that this is _not_ a destructive sort (unlike CLtL SORT), but it
- shouldn't be that hard to do the final copying into itself instead of into a
- new array.
-
- (defun sort-array-by-col (a c &optional (p #'<))
- "Sort rows of 2-dimensional array A by value of column C using predicate P"
- (let* ((num-rows (car (array-dimensions a)))
- (index-vec (do ((v (make-array num-rows))
- (i 0 (1+ i)))
- ((= i num-rows) v)
- (setf (elt v i) i)))
- (sorted-index (sort index-vec p :key #'(lambda (r) (aref a r c))))
- (new-array (make-array (array-dimensions a)))
- )
- (dotimes (r (car (array-dimensions a)))
- (dotimes (c (cadr (array-dimensions a)))
- (setf (aref new-array r c)
- (aref a (elt sorted-index r) c))))
- new-array))
-
-
- Enjoy!
-
- Bruce Krulwich
- krulwich@ils.nwu.edu
-
-
-