Double Insertion Sort is a variation on Insertion Sort that works from the middl
ID: 3924467 • Letter: D
Question
Double Insertion Sort is a variation on Insertion Sort that works from the middle of the array out. At each iteration, some middle portion of the array is sorted. On the next iteration, take the two adjacent elements to the sorted portion of the array. If they are out of order with respect to each other, then swap them. Now. push the left element toward the right in the array so long as it is greater than the element to its right. And push the right element toward the left in the array so long as it is less than the element to its left. The algorithm begins by processing the middle two elements of the array if the array is even. If the array is odd. then skip processing the middle item and begin with processing the elements to its immediate left and right. First, explain what the cost of Double Insertion Sort will be in comparison to standard Insertion sort, and why. (Note that the two elements being processed in the current iteration, once initially swapped to be sorted with respect to each other, cannot cross as they are pushed into sorted position.) Then, implement Double Insertion Sort, being careful to properly handle both when the array is odd and when it is even. Compare its running time in practice against standard Insertion Sort.Explanation / Answer
a) Cost of double insertion sort will also be O(n*n) same as insertion sort because, we have to iterate the above mentioned method n times and for each iteration the worst case time complexity can be O(n) i.e pushing till the last of the array.
b)
def double_insertion_sort(arr):
if len(arr) % 2 == 1:
#odd lenth
mid = len(arr) /2
count = 1
while mid - count >= 0:
left = mid -count
right = mid + count
if arr[left] >= arr[right]:
arr[left], arr[right] = arr[right] , arr[left]
ind = left +1
while arr[ind] <= arr[left] :
arr[left] , arr[ind] = arr[ind] , arr[left]
left +=1
ind +=1
ind =right -1
while ind >=0 and arr[ind] >= arr[right] :
arr[right] , arr[ind] = arr[ind] , arr[right]
right -=1;
ind -=1
count +=1
else:
mid = len(arr) /2
left = mid-1
right = mid
while left >= 0 and right <= len(arr) -1:
if arr[left] > arr[right]:
arr[left], arr[right] = arr[right] , arr[left]
ind = left +1
while arr[ind] < arr[left] :
arr[left] , arr[ind] = arr[ind] , arr[left]
left +=1
ind +=1
ind =right -1
while arr[ind] > arr[right] :
arr[right] , arr[ind] = arr[ind] , arr[right]
right -=1;
ind -=1
left -=1
right +=1
print arr
arr = [-8,4 ,-8 , 3, 2 , 2 , -8 , - 6 , 56 , 43, -8777]
double_insertion_sort(arr)
arr = [-8,4 ,-8 , 3, 2 , 2 , -8 , - 6 , 56 , 43, -8777, -9999999 ]
double_insertion_sort(arr)
c) running time is same as standard inserion sort.
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.