What are common array operations?

0147

Common array operations include:

  1. Traversal: Accessing each element in the array, typically using a loop.

    for (int i = 0; i < array.length; i++) {
        System.out.println(array[i]);
    }
  2. Insertion: Adding an element at a specific index. Note that arrays have a fixed size, so you may need to create a new array if you want to add more elements.

    int[] newArray = new int[array.length + 1];
    for (int i = 0; i < index; i++) {
        newArray[i] = array[i];
    }
    newArray[index] = newElement;
    for (int i = index; i < array.length; i++) {
        newArray[i + 1] = array[i];
    }
  3. Deletion: Removing an element from a specific index. Similar to insertion, this may require creating a new array.

    int[] newArray = new int[array.length - 1];
    for (int i = 0, j = 0; i < array.length; i++) {
        if (i != index) {
            newArray[j++] = array[i];
        }
    }
  4. Searching: Finding an element in the array, often using linear search or binary search (if the array is sorted).

    for (int i = 0; i < array.length; i++) {
        if (array[i] == target) {
            System.out.println("Element found at index: " + i);
            break;
        }
    }
  5. Sorting: Arranging the elements in a specific order (ascending or descending).

    Arrays.sort(array); // Sorts the array in ascending order
  6. Merging: Combining two arrays into one.

    int[] mergedArray = new int[array1.length + array2.length];
    System.arraycopy(array1, 0, mergedArray, 0, array1.length);
    System.arraycopy(array2, 0, mergedArray, array1.length, array2.length);
  7. Reversing: Changing the order of elements in the array.

    for (int i = 0; i < array.length / 2; i++) {
        int temp = array[i];
        array[i] = array[array.length - 1 - i];
        array[array.length - 1 - i] = temp;
    }

These operations are fundamental for working with arrays in Java and are commonly used in various programming tasks.

0 Comments

no data
Be the first to share your comment!