How to rearrange an array?
Hey guys, in my journey through java i ran in to a bit of a problem.
How do i rearrange a array?
Code :
// Enter values to test here
String[] s = { "from", "first", "to", "last" };
String w;
System.out.println(w);
// Enter your code here
How would i rearrange array s, to compile backwards in string w? so it would read "last to first from"?
Re: How to rearrange an array?
If all you need is all the elements of the array in reverse order then you can use a reverse loop. A normal loop would start at the first element and iterate until it reaches the last element. A reverse loop starts at the last element and iterates until it reaches the first element.
On the other hand, if you want to move elements about then you will need to copy element A into a temp variable, copy element B into the position element A was, copy the temp variable into the position element B was.
Re: How to rearrange an array?
Since you are "Compiling" into a string, you can just use a reverse loop, like Junky said, and then add the elements one at a time to w. Don't forget to add spaces!
Re: How to rearrange an array?
Quote:
Originally Posted by
jjd712
How do i rearrange a array?
Pseudo-code for one possible solution to reverse any array:
Code :
//
// Reverse elements of an array in-place.
// No extra memory required.
// Single loop goes through half of the array.
//
Define int variables i and j
Set i equal to 0, so it is indexing the first element of the array.
Set j equal to array.length-1, so that it is indexing the last element of the array.
Repeat the following loop as long as i is less than j
BEGIN LOOP
Swap array[i] and array[j];
Increment i;
Decrement j;
END LOOP
Cheers!
Z
Re: How to rearrange an array?
Thanks to everyone that helped. Worked fine!