> For the complete documentation index, see [llms.txt](https://tanias-workspace.gitbook.io/tanias-little-corner/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://tanias-workspace.gitbook.io/tanias-little-corner/problems/largest-element-in-array.md).

# Largest Element in Array

<figure><img src="/files/38RQo1p6LqNymXAu3TSX" alt=""><figcaption></figcaption></figure>

## **Swap-Based Approach**

1. **Initialize Variables:**
   * You don't need to initialize a variable to hold the maximum value directly. Instead, you'll use swaps to ensure the largest value ends up in the last position.
2. **Iterate Through the Array:**
   * Loop through the array from the beginning to the second-to-last element.
   * For each element, compare it with the next element.
3. **Swap if Necessary:**
   * If the current element is greater than the next element, swap them.
   * After each complete iteration of the array, the largest element will be in its correct position (at the end of the array).
4. **Return the Last Element:**
   * The last element of the array after the loop will be the largest.

<div align="center" data-full-width="false"><figure><img src="/files/0dIInjRlbXfg7kKNSkO7" alt=""><figcaption><p>geeksforgeeks</p></figcaption></figure></div>

#### **Time Complexity**

* **O(n^2):** This swap-based approach has a time complexity of O(n2)O(n^2)O(n2) because of the nested loops, making it less efficient than a simple linear search. However, the exercise is useful for learning and understanding how sorting-like algorithms work.

#### **Space Complexity**

* **O(1):** The algorithm uses constant extra space since it only involves swapping elements in place.

#### **Why Use Swap?**

Using swaps gives you a clear understanding of how elements can be rearranged within an array. While this isn't the most efficient method for finding the largest element, it's a useful concept when considering how more complex sorting algorithms work.
