1

I am a fairly new programmer, and want to create a method that will start with an empty array, and allow me to call on it, in order to add values to that array in ascending order.

For example:

insertInOrder(5);

insertInOrder(3);

insertInOrder(7);

insertInOrder(9);

insertInOrder(12);

should return an array with values:

0: 3

1: 5

2: 7

3: 9

4: 12

Any tips on how I can go about this without using java prebuilt methods like "Array.sort" would be much appreciated. Thank you!

Below is my attempt at this code; however, all I could implement was adding a value to the end of the array if it is the largest number.

For example:

insertInOrder(1);

insertInOrder(4);

insertInOrder(9);

insertInOrder(17);

insertInOrder(26);

would work, but this code would not:

insertInOrder(2);

insertInOrder(4);

insertInOrder(1);

insertInOrder(3);

insertInOrder(19);

Code:

public class InOrder 
{
int[] arry = new int[20];
int target = -1;
int elements = 0;

public static void main(String[] args) 
{
    InOrder i = new InOrder();
    i.insertInOrder(6);
    i.insertInOrder(7);
    i.insertInOrder(12);
    i.insertInOrder(17);
    i.insertInOrder(19);
    i.insertInOrder(28);


    for(int k = 0; k < 20; k++)
    {
        System.out.println(i.arry[k]);
    }
}

public void insertInOrder(int n) 
{

    if (elements == 0) 
    {
        arry[0] = n;
        elements++;
    }

    else 
    {
        for (int i = 0; i < elements; i++) 
        {
            if (n > arry[i]) 
            {
                target = i;
            }
        }

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

        if (n > arry[target]) 
        {
            for (int x = target; x < elements; x++) 
            {
                if(x + 1 == elements)
                {
                    arry[x + 1] = n;
                    elements++;
                    break;
                }
            }
        }
    }
}
2
  • Could you just add the item to the array and sort it? Because if the array is not sorted already then there is no point for an item to be inserted in the order, as there might be multiple correct places for it. Commented Sep 13, 2013 at 12:30
  • One thing I am confussed on: Are you saying you want to force the insertion to occur in order, or are you saying you want to insert stuff, and have it get put into order? If you are trying to keep a sorted list and if this is for a class assignment, I would recommend implementing a Linked List. Commented Sep 13, 2013 at 12:35

4 Answers 4

1

I believe you need a more complex data structure if you want to have good complexity of insertion and yet store elements in sorted order. A self-balancing binary search tree like a RB tree will work and also you can use skip list as a bit easier option.

If you do not care about complexity simply sort the array on each insert operation.

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

Comments

0

you can use this code. can change the parameter type.

public void insert(int x) {
    // loop through all elements
    for (int i = 0; i < size(); i++) {
        // if the element you are looking at is smaller than x, 
        // go to the next element
        if (get(i) < x) continue;
        // if the element equals x, return, because we don't add duplicates
        if (get(i) == x) return;
        // otherwise, we have found the location to add x
        add(i, x);
        return;
    }
    // we looked through all of the elements, and they were all
    // smaller than x, so we add ax to the end of the list
    add(x);
}

Comments

0

You can use the efficient binary search if you always insert sorted, in other words if the array always remains sorted.

import java.util.Arrays;

public class InOrder
{
  int[] array = new int[20];
  int target = -1;
  int elements = 0;

  public static void main(String[] args) 
  {
      InOrder i = new InOrder();
      i.insertInOrder(6);
      i.insertInOrder(17);
      i.insertInOrder(28);
      i.insertInOrder(19);
      i.insertInOrder(7);
      i.insertInOrder(12);

      for(int k = 0; k <i.elements; k++)
      {
          System.out.println(i.array[k]);
      }
  }

  public void insertInOrder(int n) 
  {
    if(elements==array.length) array=Arrays.copyOf(array, elements*2);
    int pos = Arrays.binarySearch(array, 0, elements, n);
    if(pos<0) pos=~pos;
    if(pos<elements) System.arraycopy(array, pos, array, pos+1, elements-pos);
    array[pos]=n;
    elements++;
  }
}

Comments

0

What you want to do is done as part of insertion sort.

High-level description:

Let the current position point to the last element
While the element to insert is smaller than the element at the current position
  Move the element at the current position right one
  Decrease the current position
Insert the element at the current position

The pseudo-code:

holePos ← length(A)
while holePos > 0 and valueToInsert < A[holePos - 1]
{ //value to insert doesn't belong where the hole currently is, so shift 
    A[holePos] ← A[holePos - 1] //shift the larger value up
    holePos ← holePos - 1       //move the hole position down
}
A[holePos] ← valueToInsert

It should be easy enough to convert to Java code.

But yes, a BST as Ivaylo suggested would be more efficient.

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.