#java insertion sort

13 messages · Page 1 of 1 (latest)

pastel thorn
#

can somone explain insertion algorithm step by step please

meager minnowBOT
#

This post has been reserved for your question.

Hey @pastel thorn! Please use /close or the Close Post button above when you're finished. Please remember to follow the help guidelines. This post will be automatically closed after 300 minutes of inactivity.

TIP: Narrow down your issue to simple and precise questions to maximize the chance that others will reply in here.

pastel thorn
#

public static void insertionSort(int arr[])

{

    int n = arr.length;



    for (int I = 1; I < n; i++)

    {   System.out.println("Sort Pass Number "+(i));

        int key = arr[i];

        int j = I-1;



        while ( (j > - 1) && ( arr [j] > key ) )

        {

        System.out.println("Comparing "+ key + " and " + arr [j]);

            arr [j+1] = arr [j];

            j- - ;

        }

        arr[j+1] = key;

        System.out.println("Swapping Elements: New Array After Swap");

        printArray(arr);

    }

}
#

like why we decreement j

#

?

meager minnowBOT
#
public static void insertionSort(int arr[])

    {

        int n = arr.length;



        for (int I = 1; I < n; i++)

        {   System.out.println("Sort Pass Number "+(i));

            int key = arr[i];

            int j = I-1;



            while ( (j > - 1) && ( arr [j] > key ) )

            {

            System.out.println("Comparing "+ key + " and " + arr [j]);

                arr [j+1] = arr [j];

                j- - ;

            }

            arr[j+1] = key;

            System.out.println("Swapping Elements: New Array After Swap");

            printArray(arr);

        }

    }
golden onyx
#

that code wont run

#

are you sure it was described exactly like that

pastel thorn
#

whatever in every insertion sort algoirthm implementation there is j--;

#

what does that mean ?

golden onyx
#

decreases j by one

last stratus
#

I would like to know how would you do this for a list