简体   繁体   中英

Inserting and Sorting in ascending order

i am trying to insert 5 numbers at a time to create an array in ascending order, but i'm having a problem with my 3rd number and so forth. The test is to insert: A number smaller than the first element A number larger than the last element A number in between the first and last element A number already in the array Here is my code so far:

import java.util.Scanner;
public class InsertInOrder {

    public static void main(String[] args) {
    Scanner input=new Scanner(System.in);
    int [] a=new int[5];
    int numberofelements=0;
    System.out.print("Number to insert: ");
    int numtoinsert=input.nextInt();
    if (numtoinsert!=0)
    {
        a[0]=numtoinsert;
        ++numberofelements;
        System.out.print("Array is now: ");
        System.out.println(a[0]);
    }
    while(numberofelements<a.length)
    {
        System.out.print("Number to insert: ");
        numtoinsert=input.nextInt();
       if ((numtoinsert<a[numberofelements]) || (numtoinsert==a[numberofelements]))
           {
              for(int i=0;i<numberofelements;i++)
              {
                  a[i]=a[i+1];
              }
           }
    else
    a[numberofelements]=numtoinsert;
    numberofelements++;
    System.out.print("Array is now: ");
    for(int i=0;i<numberofelements;i++)
        {
            System.out.print(a[i]+" ");
        }
      System.out.println();
    }
    System.out.print("\nArray is now full");
    }

}

My output of the code:

Number to insert: 5
Array is now: 5
Number to insert: 2
Array is now: 5 2 
Number to insert: 7
Array is now: 5 2 7 
Number to insert: 4
Array is now: 5 2 7 4 
Number to insert: 5
Array is now: 5 2 7 4 5 

Array is now full

This line:

if ((numtoinsert<a[numberofelements]) || (numtoinsert==a[numberofelements]))

Checks for bigger/smaller numbers in your code.

Nevertheless, numberofelements in constant in each specific iteration.

Try looping again and iterate through all the current elements in the array.

Good luck!

EDIT :

As commented below, the initial condition stated above might actually work, if the array is sorted. The sorting, however, is a bit off.

This for loop:

for(int i=0;i<numberofelements;i++)
          {
              a[i]=a[i+1];
          }

Is supposed to move the elements around in the array, making it a sorted one.

But in practice, it will just move all the elements one place backwards, and delete the first element.

Try adding the new value to it's right place in the array, without deleting other values. A bubble sort or any other sorting algorithm will do the trick.

You logic to move the values through the array is not that good.

 if ((numtoinsert<a[numberofelements]) || (numtoinsert==a[numberofelements]))
 {
     for(int i=0;i<numberofelements;i++)
     {
          a[i]=a[i+1];
     }
 }

First, remove the second condition, no need to shift the values if there are the same ;) [5;5] and [5;5] are the same ;)

Then there is two problem here :

  1. You move the values in he wrong direction
  2. You start at the beginning but the new value be inserted somewhere else

Here is what you should do :

If the new value (A) is smaller than the previous value (B). Then You need to move B to the next cell of the array. Then check again with the value before that.

Here is it in code :

if (numtoinsert < a[numberofelements-1]) { //If the PREVIOUS value is bigger
    int i = numberofelements; //start at the current index
    //then read from right to left 
    //   while not at the beginning (i > 0) 
    //   AND the value is smaller than the value at the current position.
    while(i > 0 && numtoinsert < a[i-1]) { 
        a[i] = a[i-1]; //Set the left value to the right.
        i--; //Decrement the index
    }
    a[i] = numtoinsert; //Then add the new value to the 
}

This is the full code correctly indented

public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        int[] a = new int[5];
        int numberofelements = 0;
        System.out.print("Number to insert: ");
        int numtoinsert = input.nextInt();
        if (numtoinsert != 0) {
            a[0] = numtoinsert;
            ++numberofelements;
            System.out.print("Array is now: ");
            System.out.println(a[0]);
        }
        while (numberofelements < a.length) {
            System.out.print("Number to insert: ");
            numtoinsert = input.nextInt();
            if (numtoinsert <= a[numberofelements-1]) {
                int i = numberofelements;
                while(i > 0 && numtoinsert < a[i-1]) {
                    a[i] = a[i-1];
                     i--;
                }
                a[i] = numtoinsert;
            } else {
                a[numberofelements] = numtoinsert;
            }
            numberofelements++;
            System.out.print("Array is now: ");
            for (int i = 0; i < numberofelements; i++) {
                System.out.print(a[i] + " ");
            }
            System.out.println();
        }
        System.out.print("\nArray is now full");
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM