Write a public member function in array List Type class that swap two items in the list based on their locations

Write a public member function in array List Type class that swap two items in the list based on their locations.

The correct answer and explanation is:

To swap two items in an arrayListType class, you would write a member function that accepts two indices (the locations of the items to be swapped) as arguments. The function would then swap the elements at these two indices if the indices are valid. Here’s how the code for this function might look:

void swapItems(int index1, int index2) {
    // Ensure the indices are within valid bounds
    if (index1 >= 0 && index1 < listSize && index2 >= 0 && index2 < listSize) {
        // Swap the elements
        T temp = list[index1];
        list[index1] = list[index2];
        list[index2] = temp;
    } else {
        std::cout << "Invalid indices!" << std::endl;
    }
}

Explanation:

  1. Function Signature: The function swapItems takes two integer arguments (index1 and index2), which represent the positions of the items to be swapped in the array.
  2. Bounds Checking: Before performing the swap, it checks whether both indices are valid by ensuring they are within the bounds of the array. This is important to prevent errors like accessing elements outside the array’s size. listSize is assumed to be a data member of the class that stores the number of elements in the list.
  3. Swapping: If the indices are valid, the function proceeds with the swap. It uses a temporary variable (temp) to hold one of the values during the swap process. The value at index1 is stored in temp, the value at index2 is moved to index1, and finally, temp (which holds the original value at index1) is placed at index2.
  4. Error Handling: If the indices are invalid, an error message is printed to the console, informing the user that the operation could not be performed.

This method allows the list to have two elements swapped, which can be useful in scenarios like sorting algorithms or adjusting the order of items based on certain criteria. The arrayListType class would typically be a template class (represented by T) to support different data types, making it versatile for any data type stored in the list.

Scroll to Top