0

I have the following algorithm to order an .txt file with 10 numbers

for (int i=0;i<array.length;i++)
{
    for(int j=i;j<array.length;j++)
    {
        if (array[i]<array[j])
        {
            temp=array[i];
            array[i]=array[j];
            array[j]=temp;
        }
    }
}

And it writes a new .txt file with all numbers in order. But with pen an paper it says it shouldn't work. It's the following:

7 10 4 3 5 8 1 3

The algorithm should do this:

10 7 4 3 5 8 1 3
10 8 4 3 5 7 1 3
10 8 5 3 4 7 1 3
10 8 5 4 3 7 1 3
10 8 5 4 7 3 1 3
10 8 5 4 7 3 3 1

Clearly, last line it's not in order, so why is the code doing it right? Or... where am I wrong when I doing it with pen and paper?

2
  • Algorithm is putting largest element at beginning starting for i = 0 till end. Pretty basic sorting algorithm with complexity of O(n2) Commented Jul 24, 2013 at 16:45
  • Wow, took me a while to see that it is not Bubble Sort. Commented Jul 24, 2013 at 21:37

3 Answers 3

5

Why it should not work? It's a pretty basic sorting algorithm (called selection sort). The problem with your pen and pencil is that you're forgetting about the outer for. Which continue sorting for every item. That's why its O(n^2) in complexity.

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

Comments

0

I would re-check your third result:

10 8 5 3 4 7 1 3

You ended up with '5' as your third digit after it swapped the '4' out, but this is not finished. If you keep iterating the 'j' loop it will continue testing the rest of the digits. If we were to run that loop properly it would look more like this:

Starting with 10 8 4 3 5 7 1 3 where i points to the third digit '4':
if (4 < 4) false  // This is an unecessary step FYI, should start the loop with j=i+1
if (4 < 3) false
if (4 < 5) true, swap 4 with 5 = 10 8 5 3 4 7 1 3
  // This is where you seem to have stopped your loop and jumped directly to the next i,
  // However, there is no break and the j loop should continue on using the new third
  // digit '5'...
if (5 < 7) true, swap 5 with 7 = 10 8 7 3 4 5 1 3
if (7 < 1) false
if (7 < 3) false

You end up with the result 10 8 7 3 4 5 1 3 as your third iteration.

Comments

0

Why wouldn't it work? For each position i, the inner loop effectively moves the largest member of the rest of the list to that location (making it a selection sort).

I think your paper walkthrough went wrong on the third step; I get:

7 10 4 3 5 8 1 3 <- original list
^i
10 7 4 3 5 8 1 3
   ^i
10 8 4 3 5 7 1 3
     ^i
10 8 7 3 4 5 1 3
       ^i
10 8 7 5 3 4 1 3
...

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.