home *** CD-ROM | disk | FTP | other *** search
- Path: sparky!uunet!mcsun!uknet!icdoc!sot-ecs!sra
- From: sra@ecs.soton.ac.uk (Stephen Adams)
- Newsgroups: comp.programming
- Subject: in-place merge
- Message-ID: <SRA.92Jul30223243@nansen.ecs.soton.ac.uk>
- Date: 30 Jul 92 21:32:43 GMT
- Sender: news@ecs.soton.ac.uk
- Organization: Southampton University Computer Science
- Lines: 57
- Nntp-Posting-Host: nansen
-
- Does anyone know of an O(n) time and O(1) space algorithm
- for doing an in-place merge, or have a proof that it is not
- possible?
-
- By an in-place merge I mean the following:
-
- Given
-
- . an array a[1:n] of n elements
- . k such that 1<=k<=n-1
- . a[1:k] is sorted
- . a[k+1:n] is sorted
-
- I want to merge the two sorted lists a[1:k] and a[k+1:n],
- resulting in a single sorted list a[1:n], by re-arranging
- the elements of a (i.e. in-place). You are allowed only to
- use a fixed amount of extra storage.
-
- The only algorithms I know of for merging assume either a
- separate destination array, or pointers that link the
- elements together, as in linked lists.
-
- I can think of an O(n^2) time algorthim:
-
- p := 1; // `head' for first list
- q := k+1; // `head' of second list
-
- while q<n do
- if a[p] <= a[q] then
- // a[p] is in the correct position
- p := p+1
- else
- // must move all of the first list to make a
- // space for a[q]
- for i:= q-1 downto p do a[i] := a[i-1];
- a[p] := a[q];
- p:=p+1;
- q:=q+1;
- end if
- end
-
- This is clearly O(n^2): if k=n/2 and a[1]>a[k+1] then the
- lists end up by being swapped. All of the first list is
- moved, one place at a time, to the position of the second
- list. This is k moves of k words = n^2/4, assignments.
- Space is O(1) as we only use indexes p, q and i.
-
-
- I am prepared to relax the problem:
-
- . k is near, or exactly n/2
- . O(log n) space
- --
- Stephen Adams Email: S.R.Adams@ecs.soton.ac.uk
- Electronics and Computer Science Tel: 0703 593649
- University of Southampton Fax: 0703 593045
- Southampton SO9 5NH, UK
-