Open In App

# Python program to insert an element into sorted list

Given a sorted list and an element, Write a Python program to insert the element into the given list in sorted position.

Examples:

```Input : list = [1, 2, 4], n = 3
Output : list = [1, 2, 3, 4]

Input : list = ['a', 'b', 'c', 'd'], n = 'e'
Output : list = ['a', 'b', 'c', 'd', 'e']```

Approach #1 : This approach is the brute force method. Since the list is already sorted, we begin with a loop and check if the list element is greater than the given element. If yes, the given element need to be inserted at this position.

## Python3

 `# Python3 program to insert``# an element into sorted list` `# Function to insert element`  `def` `insert(``list``, n):` `    ``index ``=` `len``(``list``)``    ``# Searching for the position``    ``for` `i ``in` `range``(``len``(``list``)):``      ``if` `list``[i] > n:``        ``index ``=` `i``        ``break` `    ``# Inserting n in the list``    ``if` `index ``=``=` `len``(``list``):``      ``list` `=` `list``[:index] ``+` `[n]``    ``else``:``      ``list` `=` `list``[:index] ``+` `[n] ``+` `list``[index:]``    ``return` `list` `# Driver function``list` `=` `[``1``, ``2``, ``4``]``n ``=` `3` `print``(insert(``list``, n))`

Output:

`[1, 2, 3, 4]`

Time Complexity: O(N)
Auxiliary Space: O(1)

Approach #2 : Python comes with a bisect module whose purpose is to find a position in list where an element needs to be inserted to keep the list sorted. Thus we use this module to solve the given problem.

## Python3

 `# Python3 program to insert``# an element into sorted list``import` `bisect` `def` `insert(``list``, n):``    ``bisect.insort(``list``, n)``    ``return` `list` `# Driver function``list` `=` `[``1``, ``2``, ``4``]``n ``=` `3` `print``(insert(``list``, n))`

Output:

`[1, 2, 3, 4]`

Time Complexity: O(N)
Auxiliary Space: O(1)

Approach #3 : Another way to insert an element into a sorted list is to use the built-in sorted() function. This function takes an iterable and returns a sorted list. We can pass the original list and the element to be inserted as arguments to the sorted() function, and it will return a new sorted list with the element inserted at the correct position.

## Python3

 `def` `insert(``list``, n):``  ``# Insert the element into the list``  ``list``.append(n)``  ``# Sort the list``  ``sorted_list ``=` `sorted``(``list``)``  ``return` `sorted_list` `list` `=` `[``1``, ``2``, ``4``]``n ``=` `3``print``(insert(``list``, n))``#This code is contributed by Edula Vinay Kumar Reddy`

Output

`[1, 2, 3, 4]`

Time Complexity: O(Nlog(N)) since the sorted() function uses a sorting algorithm with a time complexity of O(Nlog(N))
Auxiliary Space: O(N) since the sorted() function creates a new list with the same size as the original list

#### Approach#4: Using while loop

This approach first appends the new element to the end of the list, then iterates from the end of the list to the beginning. For each pair of adjacent elements, if the element on the right is smaller than the element on the left, the two elements are swapped. This process continues until either the beginning of the list is reached or a pair of adjacent elements is found where the element on the right is greater than or equal to the element on the left. This ensures that the list remains sorted after the new element is inserted.

#### Algorithm

1. Define a function named ‘insert_sorted’ that takes a list ‘lst’ and an element ‘n’ as input.
2. Append the element ‘n’ to the list ‘lst’.
3. Initialize a variable ‘i’ with the last index of the list.
4. Loop through the list from the last index to the first index and swap adjacent elements if they are not in sorted order until the first element is reached or the adjacent elements are in sorted order.
5. Return the updated list ‘lst’.
6. Define the input list and the element to be inserted for each test case.
7. Call the ‘insert_sorted’ function for each test case and print the updated list.

## Python3

 `def` `insert_sorted(lst, n):``    ``lst.append(n)``    ``i ``=` `len``(lst) ``-` `1``    ``while` `i > ``0` `and` `lst[i] < lst[i``-``1``]:``        ``lst[i], lst[i``-``1``] ``=` `lst[i``-``1``], lst[i]``        ``i ``-``=` `1`  `lst ``=` `[``'a'``, ``'b'``, ``'c'``, ``'d'``]``n ``=` `'e'``insert_sorted(lst, n)``print``(lst)`

Output

`['a', 'b', 'c', 'd', 'e']`

Time complexity: O(n), where n is the length of the list.
Auxiliary Space: O(1), as the list is modified in-place.

Approach #5: Using heapq.heappush() function

Python’s heapq module implements heap queue algorithm. The most important feature of a heap is that the element with the highest priority is always at the root of the heap, and any operations to add or remove elements take O(log n) time where n is the number of elements in the heap. This makes heapq a great candidate for this problem.

1. Define a function named ‘insert_sorted’ that takes a list ‘lst’ and an element ‘n’ as input.
2. Append the element ‘n’ to the list ‘lst’.
3. Use heapq.heapify() function to convert the list into a heap in O(n) time.
4. Use heapq.heappush() function to insert the new element ‘n’ into the heap in O(log n) time.
5. Use a list comprehension to convert the heap back into a sorted list.
6. Return the sorted list.
7. Define the input list and the element to be inserted for each test case.
8. Call the ‘insert_sorted’ function for each test case and print the updated list.

## Python3

 `import` `heapq` `# Function to insert in the sorted order``def` `insert_sorted(lst, n):``    ``lst.append(n)``    ` `    ``# Convert the list to a heap``    ``heapq.heapify(lst)``    ``# Use heapq.heappop() function to``    ``# convert the heap into a sorted``    ``# list``    ``sorted_lst ``=` `[heapq.heappop(lst) ``for` `i ``in` `range``(``len``(lst))]``    ``return` `sorted_lst`  `# Driver Code``lst1 ``=` `[``1``, ``2``, ``4``]``n1 ``=` `3``print``(insert_sorted(lst1, n1))` `lst2 ``=` `[``'a'``, ``'b'``, ``'c'``, ``'d'``]``n2 ``=` `'e'``print``(insert_sorted(lst2, n2))`

Output

```[1, 2, 3, 4]
['a', 'b', 'c', 'd', 'e']```

Time Complexity: O(n log n) since the heapq.heappop() function is used to convert the heap into a sorted list
Auxiliary Space: O(n) since a heap is created from the input list

METHOD 6:Using Quicksort method

APPROACH:

The code above implements the quicksort algorithm to sort a list of integers and insert a new integer element n at the correct position in the sorted list.

ALGORITHM:

1.The quicksort algorithm sorts the list in place by partitioning it into two sub-lists around a pivot element, and then recursively sorting the sub-lists until the entire list is sorted.
2.The partitioning process involves selecting a pivot element from the list and then reordering the list such that all elements less than the pivot appear before it, and all elements greater than the pivot appear after it.
3.This process is then repeated on the two sub-lists until the entire list is sorted.

## Python3

 `def` `quicksort(lst):``    ``if` `len``(lst) <``=` `1``:``        ``return` `lst``    ``pivot ``=` `lst[``len``(lst) ``/``/` `2``]``    ``left ``=` `[x ``for` `x ``in` `lst ``if` `x < pivot]``    ``middle ``=` `[x ``for` `x ``in` `lst ``if` `x ``=``=` `pivot]``    ``right ``=` `[x ``for` `x ``in` `lst ``if` `x > pivot]``    ``return` `quicksort(left) ``+` `middle ``+` `quicksort(right)` `lst ``=` `[``1``, ``2``, ``4``]``n ``=` `3` `# Insert the new element at the appropriate index``sorted_lst ``=` `quicksort(lst ``+` `[n])``index ``=` `sorted_lst.index(n)``lst.insert(index, n)` `print``(lst)`

Output

`[1, 2, 3, 4]`

Time complexity:

1.The worst-case time complexity of quicksort is O(n^2), which occurs when the pivot is chosen poorly and partitions the list into sub-lists of uneven size.
2.However, on average, quicksort has a time complexity of O(n log n), which makes it a very efficient sorting algorithm.

Space complexity:

1.The space complexity of quicksort is O(log n) on average, as it requires recursive function calls and space for the call stack.
2.However, in the worst case (when the recursion depth is equal to the length of the list), the space complexity can be as high as O(n).

### Using insert() method:

Approach:

Define a function insert_element_in_sorted_list that takes a sorted list lst and an element n as input.
Iterate over the indices of the list using a for loop and the range() function.
For each index i, check if the element at that index is greater than the element n.
If the element at index i is greater than n, insert n at index i using the insert() method of the list and return the modified list.
If all elements in the list are less than or equal to n, append n to the end of the list and return the modified list.

Here are the steps applied to the example input list1 and n1:

list1 is [1, 2, 4] and n1 is 3.
The function iterates over the indices 0, 1, and 2.
At index 2, the element 4 is greater than n1 so the function inserts n1 at index 2 using the insert() method, resulting in the modified list [1, 2, 3, 4].
The modified list is returned and printed, resulting in the output [1, 2, 3, 4].
Here are the steps applied to the example input list2 and n2:

list2 is [‘a’, ‘b’, ‘c’, ‘d’] and n2 is ‘e’.
The function iterates over the indices 0, 1, 2, and 3.
At index 3, the element d is less than n2 so the function appends n2 to the end of the list, resulting in the modified list [‘a’, ‘b’, ‘c’, ‘d’, ‘e’].
The modified list is returned and printed, resulting in the output [‘a’, ‘b’, ‘c’, ‘d’, ‘e’].

## Python3

 `def` `insert_element_in_sorted_list(lst, n):``    ``for` `i ``in` `range``(``len``(lst)):``        ``if` `lst[i] > n:``            ``lst.insert(i, n)``            ``return` `lst``    ``lst.append(n)``    ``return` `lst` `# Example usage:``list1 ``=` `[``1``, ``2``, ``4``]``n1 ``=` `3``print``(insert_element_in_sorted_list(list1, n1)) ``# Output: [1, 2, 3, 4]` `list2 ``=` `[``'a'``, ``'b'``, ``'c'``, ``'d'``]``n2 ``=` `'e'``print``(insert_element_in_sorted_list(list2, n2)) ``# Output: ['a', 'b', 'c', 'd', 'e']`

Output

```[1, 2, 3, 4]
['a', 'b', 'c', 'd', 'e']```

The time complexity of this approach is O(n) in the worst-case scenario, where n is the length of the list. This is because we may need to traverse the entire list to find the appropriate position to insert the element.

The auxiliary space of this approach is O(1) as we are not creating any new data structures.