-4

I changed my program a little. The new problem is that the execution doesn't stop!

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package inplacesort;

import java.util.*;
/**
 *
 * @author ASUS
 */
public class InplaceSort 
{
    static Scanner console = new Scanner(System.in);

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args)
    {
        Vector <Integer> intList = new Vector <Integer> ();

        //getting the numbers from the user
        char ans = 'y';

        while (ans == 'Y' || ans == 'y')
        {
            System.out.print("Enter a Number: ");
            intList.addElement(console.nextInt());

            System.out.print("Do You Want to Continue?(Y/N)");
            ans = console.next().charAt(0);
        }
        System.out.println(intList);
        for (int i = 1; i < intList.size(); i++)
        {
            //if (intList.elementAt(i) < intList.elementAt(i-1))
            //{
            int j = i - 1;
            while (j >= 0 && intList.elementAt(i) < intList.elementAt(j))
            {
                j--;
            }

            if (j == -1)
            {
                j = 0;
            }

            for (int k = intList.size() - 1; k >= j; k--)
            {
                intList.insertElementAt(intList.elementAt(k),k + 1);
            }

            intList.insertElementAt(intList.elementAt(i+1),j);
            intList.removeElementAt(i+1);
            //}
        }
        System.out.print(intList);
    }
}
FrustratedWithFormsDesigner
  • 26,726
  • 31
  • 139
  • 202
Parisa
  • 159
  • 1
  • 2
  • 8
  • 1
    Give us a stacktrace, please. – Dirk Lachowski Sep 11 '14 at 11:44
  • 3
    `i <= (intList.size())-1` is a *really* convoluted way to write `i < intList.size()`. – T.J. Crowder Sep 11 '14 at 11:45
  • 1
    Can you add the stacktrace and the input data so we can try it? – Jens Sep 11 '14 at 11:46
  • I have to get back to work, but I'm fairly sure you want a `- 1` on this line: `intList.removeElementAt(i);` (since you just inserted in front of it). – T.J. Crowder Sep 11 '14 at 11:46
  • Sorry, one last thing: This isn't an [insertion sort](http://en.wikipedia.org/wiki/Insertion_sort) as implied by the name of your class. It would be an insertion sort if you built a *new* `Vector` (or, ideally, `List`) by looping through the first one, inserting each element in the right place. So if this is for homework, you might want to double-check the assignment: If the instructor wants an insertion sort, this is probably not going to be what they're looking for. – T.J. Crowder Sep 11 '14 at 11:48
  • On the line `if (j < 0)` your `j` is zero. In the next line, your `j` becomes `-1`. `intList.insertElementAt(intList.elementAt(i),j);` will throw a `ArrayIndexOutOfBoundsException`, because your `j` is `-1`. – Alexander_Winter Sep 11 '14 at 11:49
  • possible duplicate of [What is a stack trace, and how can I use it to debug my application errors?](http://stackoverflow.com/questions/3988788/what-is-a-stack-trace-and-how-can-i-use-it-to-debug-my-application-errors) – Raedwald Sep 11 '14 at 12:07
  • Parisa, did you even bother to look at the question after your edit? – T.J. Crowder Sep 11 '14 at 12:52
  • I added the photo of the trace back T.J. Crowder – Parisa Sep 11 '14 at 12:59

5 Answers5

2

Without the stack trace I don't know if this is the specific issue you've hit as I saw several things that looked a bit off. This is definitely wrong though:

       while(intList.elementAt(i) < intList.elementAt(j))
            {
                if (j < 0)
                {
                    break;
                }
                j--;
            }

You decrement j, then you fetch the element at j, then you check for < 0 having already used it.

Tim B
  • 40,716
  • 16
  • 83
  • 128
1

Your internal while cycle decreases the variable j without checking if it's not negative. Negative indices are invalid for indexing arrays and Vectors.

At least add j >= 0 to the condition:

while(j >= 0 && intList.elementAt(i) < intList.elementAt(j))
            {
                if (j < 0)
                {
                    break;
                }
                j--;
            }

After this the internal if is no longer required so simply:

while (j >= 0 && intList.elementAt(i) < intList.elementAt(j))
    j--;
icza
  • 389,944
  • 63
  • 907
  • 827
  • With having added the check into the expression in the while loop the if() is completely redundant and can be removed. – Tim B Sep 11 '14 at 11:51
1

it was due to (int i = 1; i <= (intList.size())-1; i++) you had initialized i with 1 and subtracted list size again with 1

package test;
import java.util.*;
public class InsertionSort 
{
    static Scanner console = new Scanner(System.in);

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args)
    {
        Vector <Integer> intList = new Vector <Integer> ();

        //getting the numbers from the user
        char ans = 'y';

        while(ans == 'Y' || ans == 'y')
        {
            System.out.print("Enter a Number: ");
            intList.addElement(console.nextInt());

            System.out.print("Do You Want to Continue?(Y/N)");
            ans = console.next().charAt(0);
        }

        for (int i = 0; i <intList.size(); i++)
        {
            if (intList.elementAt(i) < intList.elementAt(i))
            {
                int j = i - 1;
                while(intList.elementAt(i) < intList.elementAt(j))
                {
                    if (j < 0)
                    {
                        break;
                    }
                    j--;
                }
                intList.insertElementAt(intList.elementAt(i),j);
                intList.removeElementAt(i);
            }
        }
        System.out.print(intList);
    }
}
Shreeraj Karki
  • 234
  • 2
  • 11
0

Your while loop should break if j is lower than 1 (or equals 0). Then your code works fine:

while(intList.elementAt(i) < intList.elementAt(j))
            {
                if (j < 1)
                {
                    break;
                }
                j--;
            }
Jens
  • 67,715
  • 15
  • 98
  • 113
0

Here the Mistake is on the line while(j>0 && intList.elementAt(i) < intList.elementAt(j))

You have specified j>=0 , which will give j value as -1 when going inside the while loop

Rectifing the above mistake , the program will execute , but your sorting have Some issues , as its not sorting .

Revamped Code:

package com.example.poly;

/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */

import java.util.; /* * * @author ASUS */ public class InsertSort { static Scanner console = new Scanner(System.in);

/**
 * @param args the command line arguments
 */
public static void main(String[] args)
{
    Vector <Integer> intList = new Vector <Integer> ();

    //getting the numbers from the user
    char ans = 'y';

    while(ans == 'Y' || ans == 'y')
    {
        System.out.print("Enter a Number: ");
        intList.addElement(console.nextInt());

        System.out.print("Do You Want to Continue?(Y/N)");
        ans = console.next().charAt(0);
    }

    for (int i = 1; i <= (intList.size())-1; i++)
    {
        if (intList.elementAt(i) < intList.elementAt(i-1))
        {
            int j = i - 1;
            while(j>0 && intList.elementAt(i) < intList.elementAt(j))
            {
                j--;
            }
            intList.insertElementAt(intList.elementAt(i),j);
            intList.removeElementAt(i);
        }
    }
    System.out.print(intList);
}

}

Manojkumar
  • 96
  • 5