Tilak Raj Singh
Tilak Raj Singh

Reputation: 353

sorting an array to make it a circular one

I have an array, and I can exchange only ith and i+1th element. How can I sort this array into a circular one using minimum number of exchange operations?

For example my array is:-

3 5 4 2 1

Then exchanging 2nd and 3rd I get

3 4 5 2 1

And then exchanging 4th and 5th I get

3 4 5 1 2 

which is the required sorted circular array in 2 exchanges.

Another example

4 3 5 1 2

Here just one exchange of 1st and 2nd gives me 3 4 5 1 2

What algorithm should I use to achieve this?

Upvotes: 2

Views: 533

Answers (1)

subhash
subhash

Reputation: 39

You can use for loop with a temp variable then sort it all array elements , but for loop should be increment by 2 .

len=array[(array.length)];
for (i=1 ; i<len - 1 ; i=i+2 ){
    temp=array[i];
    array[i]=array[i+1];
    array[i+1]=temp;    
}
temp=array[0];
array[o]=array[len];
array[len]=temp;

this simple algorithm will work in java and sorts array perfectly as you required.

Upvotes: 1

Related Questions