Member Avatar for Ajantis

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

>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.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.