-2

Possible Duplicate:
Reordering of array elements
Interview test - rearrange the array

I have an array where three semantic elements (a,b,c) are stored in the form:

[a][b][c][a][b][c][a][b][c]...

This means that a b and c are not actual values. The first a might be 10, the second 1, the third 25, and so on. a b and c says that the program will give all indices where you see an "a" a certain semantic meaning, the same for b and c.

I want to reorder so it has the form:

[a][a][a]...[b][b][b]...[c][c][c].... 

Is there a way to do this "in-place", meaning without the usage of a temporary "buffer" array?

An example with values:

Starting array:

[11][5][3][284][123123][841823][0][11][22]

I need to reorder it to:

[11][284][0][5][123123][11][3][841823][22]

5
  • 1
    This Wikipedia article may answer your question: In-place matrix transposition. Commented Nov 30, 2012 at 14:45
  • 2
    Most sorting algorithms, from bubblesort to quicksort, are done in place. Commented Nov 30, 2012 at 14:46
  • hmm.. quicksort, mergesort or any of the other ones Commented Nov 30, 2012 at 14:46
  • en.wikipedia.org/wiki/Sorting_algorithm Commented Nov 30, 2012 at 14:46
  • It's not about sorting. Perhaps I should have been more clear. The a,b and c elements are semantic elements, not the actual values inside the array. I will update the question :-) Commented Nov 30, 2012 at 14:50

1 Answer 1

0

There is an O(n.lgn) time divide-and-conquer algorithm with O(1) additional memory usage:

Assume that you want to reorder the 3n-sized array bellow:

A=[1,n+1,2n+1, 2,n+2,2n+2, ... , n,2n,3n].

Divide A into two subarrays A1 and A2, A1 including indices numbered from 1 to 3*[n/2], and A2 including indices 3*[n/2]+1 to 3n. Reorder A1 and A2 (in-place) recursively. Then, A becomes something like a 6-parted array [p1,p3,p5,p2,p4,p6] that each part is a correctly-ordered subarray of consequent elements and you can just re-order them into [p1,p2,p3,p4,p5,p6] in O(n) in-place with swap operations.

T(n)=2T(n/2)+O(n)=O(n lgn)

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.