finding best and wost case in Insertion Sort
1 view (last 30 days)
Show older comments
I have a code from mathworks for insertion sort
function sorted = insertion_sort(unsorted)
array_size = size(unsorted,2);
for pivot = 2:array_size
for j = 1:pivot-1
if (unsorted(j)>unsorted(pivot))
temp = unsorted(pivot);
unsorted (j+1:pivot) = unsorted (j:pivot-1);
unsorted(j) = temp
end
end
end
sorted = unsorted;
end
suppose mu unsorted value is [5 1 2 9 7 3 8 ]
kindly tell how to calculate best worst and average case
0 Comments
Answers (1)
Roger Stafford
on 28 Jul 2013
It is not clear what you are asking. With a given array such as the one you describe, there can be no "best" or "worst" case. The amount of processing is exactly determined by that array.
In general the worst cases will occur when the initial array is entirely descending and the best cases would be those in which the initial array is already ascending. That is because the amount of shifting in the line
unsorted (j+1:pivot) = unsorted (j:pivot-1);
is maximized or minimized in the two respective cases.
However, this sorting algorithm is far from optimum since it is of order n^2 operations with n the length of the array. An efficient algorithm such as "merge" sorting can accomplish a sort operation with only order n*log(n) operations, and for a large array this can be significantly fewer operations.
0 Comments
See Also
Categories
Find more on Matrices and Arrays in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!