0

Hey there :)

I need a little enlightenment over this one... I took a snippet from the Mark Allen Weiss' book - Data structures & Problem solving using Java... but I didn't understand it really.

Here's the code:

1./**
2.* Simple insertion sort
3.*/
4.public static <AnyType extends Comparable<? super AnyType>>
5.void insertionSort( AnyType [] a )
6.{
7.        for( int p = 1; p < a.length; p++ )
8.        {
9.                AnyType tmp = a[ p ];
10.                int j = p;
11. 
12.                for ( ; j > 0 && tmp.compareTo( a[ j - 1 ] ) < 0; j-- )
13.                        a[ j ] = a[ j - 1 ];
14.                a[ j ] = tmp;
15.        }
16.}

What I don't understand is... why is he using a[j] = tmp; at line 14?? Won't it reset the value given by the code in line 13?? :S

2
Contributors
1
Reply
2
Views
7 Years
Discussion Span
Last Post by Narue
0

>why is he using a[j] = tmp; at line 14?? tmp is the value being inserted. The loop prior to a[i] = tmp; is simply a shift to make room for the new value.

>Won't it reset the value given by the code in line 13??
No. Step through the code with a debugger to see how it works, and note that at the end of a for loop, the counter is updated.

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.