This week's giveaway is in the Android forum.
We're giving away four copies of Android Security Essentials Live Lessons and have Godfrey Nolan on-line!
See this thread for details.
The moose likes Programming Diversions and the fly likes Can we sort using a single loop? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Android Security Essentials Live Lessons this week in the Android forum!
JavaRanch » Java Forums » Other » Programming Diversions
Bookmark "Can we sort using a single loop?" Watch "Can we sort using a single loop?" New topic
Author

Can we sort using a single loop?

Pavan Kumar Dittakavi
Ranch Hand

Joined: Feb 12, 2011
Posts: 104

Hi All,

I want to know if this is possible:" Writing a program that sorts an array by using only a single loop."; I dont want the solution but I wanted to know if this is really feasible.

Thanks,
Pavan.
anirudh jagithyala
Ranch Hand

Joined: Dec 07, 2010
Posts: 41


where 'x' is the integer array name, 'n' is the number of elements in 'x'.
This for loop sorts the elements of the array in ascending order. To sort in descending order, change "if ( x[ i ] < x[ i + 1 ] )" to "if ( x[ i ] > x[ i + 1 ] )"

I have no way of testing all of these, but I'm pretty sure they'll work.
Pavan Kumar Dittakavi
Ranch Hand

Joined: Feb 12, 2011
Posts: 104

I think I have got it.


@anirudh jagithyala: The code you provided fails for input 5 1 7 3 9. Thanks anyway.

Thanks,
-Pavan.
Ryan McGuire
Ranch Hand

Joined: Feb 18, 2005
Posts: 1006
    
    3
Pavan Kumar Dittakavi wrote:Hi All,

I want to know if this is possible:" Writing a program that sorts an array by using only a single loop."; I dont want the solution but I wanted to know if this is really feasible.

Thanks,
Pavan.


Short answer: Any algorithm can be reworked as a single loop.

For this problems, you can implement what amounts to a bubble sort by using two indices (say i and j) and just have all the initialization, incrementing and termination expressions in a handful of if/then/else statements at the bottom of the single loop. It would still execute in O(n^2) time, but it would technically be a single loop.
 
wood burning stoves
 
subject: Can we sort using a single loop?
 
Similar Threads
loops in ant script
while Loop
Can we put EL in a for loop?
jstl - breakig out of a loop early
function like cleardevice() in java