0
package basic;

public class SortingAlgs {

 public static void main(String[] args) {
    int[] arr3 = { 5, 17, 21, 35, 3, 10, 7, 2, 31, 40, 80 };
    arr3 = selectionSort(arr3);
    print(arr3);
 }

 public static void print(int[] arr) {
    for (int num : arr) 
        System.out.print(num + " ");
    System.out.println();
 }  

 public static int[] selectionSort(int[] arr)
 {
     for (int i = arr.length - 1; i >= 0; i--)
     {
         int maxIndex = 0;
         for (int j = 1; j <= i; j++)
         {
             if (arr[j] > arr[maxIndex])
                 maxIndex = j;
         }
         int temp = arr[maxIndex];
         arr[maxIndex] = arr[i];
         arr[i] = temp;
     }
     return arr;

 }

This code returns

(23 57 10 17 21 31 35 40 80)

So I want to add an new array elements, example

(23 57 10 17 21 31 35 40 80 -- 83 98 100 )
PEHLAJ
  • 9,980
  • 9
  • 41
  • 53

3 Answers3

1

Try using an ArrayList with an object of Integer Array list is resizing itself whenever a new object is added

ArrayList<Integer> numbers= new ArrayList<Integer>(); then numbers.add(Integer.valueOf(5));

review the ArrayList class here https://docs.oracle.com/javase/7/docs/api/java/util/ArrayList.html

PEHLAJ
  • 9,980
  • 9
  • 41
  • 53
0xDEADBEEF
  • 590
  • 1
  • 5
  • 16
1

You can use java.lang.System.arraycopy() method for writing a function like below.

public static int[] addElement(int[] originalArray, int newElem){

    int[] elementArray = new int[]{newElem};
    int[] newArray = new int[originalArray.length + 1];

    System.arraycopy(originalArray,0, newArray,0, originalArray.length);
    System.arraycopy(elementArray,0, newArray, originalArray.length, 1);

    return newArray;
}

Please have a look at this.

PEHLAJ
  • 9,980
  • 9
  • 41
  • 53
0

You cannot change the existing array.

Try using List<Integer> if you want to add/remove items dynamically.

PEHLAJ
  • 9,980
  • 9
  • 41
  • 53