Algorithm - the time complexity of deletion in a unsorted array

后端 未结 4 1086
庸人自扰
庸人自扰 2021-01-01 03:29

Suppose there is a unsorted array A, and it contains an element x (x is the pointer of the element), and every element has a satellite variable k. So, we can get the followi

相关标签:
4条回答
  • 2021-01-01 04:20

    Finding the element with a given value is linear.

    Since the array isn't sorted anyway, you can do the deletion itself in constant time. First swap the element you want to delete to the end of the array, then reduce the array size by one element.

    0 讨论(0)
  • 2021-01-01 04:24

    Worst case time complexity for deletion operation in a sorted array is O(n), If the array is not sorted and it is mentioned that after deletion operation order of the array shouldn't be altered then time complexity will be same as O(n) otherwise it will be O(1).

    0 讨论(0)
  • 2021-01-01 04:25

    Yes. It takes O(n) time to find the element you want to delete. Then in order to delete it, you must shift all elements to the right of it one space to the left. This is also O(n) so the total complexity is linear.

    Also, if you're talking about statically allocated arrays, insert takes O(n) as well. You have to resize the array in order to accommodate the extra element. There are ways to amortize this running time to O(1) though.

    0 讨论(0)
  • 2021-01-01 04:35

    Yes, that's right. Also, if it's an array, deleting alone will take O(n) time because after you delete the element, you'll need to shift all the elements to the right of that element one place to the left. So, even if you know x (for example, you will only delete the first element), it will take O(n) time.

    0 讨论(0)
提交回复
热议问题