Posts

Showing posts with the label Insert an element in a sorted array.

Insert an element in a sorted array

Image
# Insert an element in a sorted array: To insert an element in a sorted array, We have to start comparing the key element with the last element of the array and if the last element is greater than the key element then shift the last element to its next index. This procedure we have to follow until we find the element in array equal to or smaller than the key element. like if we need to insert 5 in below array: then we have to take a variable "i" and "i" will be initialized by array length - 1 So i = A.length - 1 = 5 - 1 = 4; So 5 is compared with A[4], as A[4] is 8 so 8 > 5 , then we have to shift A[i] to A[i+1], A[i+1] = A[i] // A[5] = A[4] // A[5] = 8  and A[4] is empty. and need to do --i, so i will be 3 now now again we have to compare 5 with A[3], as A[3] is 7 and 7 > 5 , So again we have to shift it to the next index. A[i+1] = A[i]; // A[4] = A[3] // A[4] = 7  and A[3] is empty. --i; So i will be 2 now now again we have to compare 5 with A[2], as A[2] is...