This week's book giveaway is in the Servlets forum.
We're giving away four copies of Murach's Java Servlets and JSP and have Joel Murach on-line!
See this thread for details.
The moose likes Beginning Java and the fly likes simple sorting algorithm Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of Murach's Java Servlets and JSP this week in the Servlets forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "simple sorting algorithm" Watch "simple sorting algorithm" New topic

simple sorting algorithm

Max Rauschebart

Joined: Sep 26, 2010
Posts: 1
Hey guys,

I got this little code which should actually sort the numbers in an array from the smallest to the highest,

At least I dont get any error messages (yeah!) but the result ist not sorted.

It must have to do with the two for loops (is this the right term for it in English?)

I hope you guys could give me a hint

Greetings from Germany

Rob Spoor

Joined: Oct 27, 2005
Posts: 19649

When I run your code there are only two values out of place: 3 and 4. The 3 makes sense; you start both i and j at 1, thereby always ignoring location 0. If I let both start at 0 then only 4 is out of place. That is not coincidentally the last element when you start.

How To Ask Questions How To Answer Questions
Sudipta Laha
Ranch Hand

Joined: Aug 23, 2010
Posts: 49

The logic is not correct.

PLease find the bellow steps
1. For loop from 0 to end of size of loop(u should start with 0)
2. 2nd for loop that should start with the i+1 to end of loop.
3. them make the comparison between the elements of two loops.

I believe its not clear..

Look for each element in first loop you need to compare the elements of the array(thats what is the 2nd loop for) and then select the least element(by giving 'if' condition in the 2nd loop). Now you need set the least element in the 1st position and the 1st position element in the place of least element. When the two loops completes you get the sorted array.

Try to implement this. It will work.

Sudipta Kumar Laha
It is sorta covered in the JavaRanch Style Guide.
subject: simple sorting algorithm
Similar Threads
summing each row in a 2-dimensional array
SoDuko puzzle
array question
Something i'm extremely confused on