Moderators: phlip, Larson, Moderators General, Prelates
#!usr/bin/perl
use warnings;
use strict;
my @array = (4, 6, 3, 7, 5, 9);
my $key;
my $i;
my $x;
for($x = 1; $x < $#array; $x++){
$key = $array[$x];
$i = $x;
while($i > 0 and $array[$i-1] > $key){
print "@array \n";
$array[$i] = $array[$i - 1];
$i--;
print "@array \n";
}
$array[$i] = $key;
}
print "@array \n";quintopia wrote:With an algorithm like insertion sort, analyzing the running time is even easier than proving the correctness
The outer loop happens n times for array of length n.
The inner loop happens at most n times (because you can't do worse than moving the last element to the beginning).
Thus the inner loop runs less than n*n times, which means the algorithm is O(n2).
I'm not trying to spoonfeed you answers or anything (which I can't do really, because the answers are all right there in the book), just illustrate how I go about thinking about algorithms.
Xanthir wrote:Frex, quicksort is usually reported as O(n*log(n)), but really it's O(n2), just like any other generic sort. The difference is that quicksort is *almost always* roughly n*log(n), except when it hits certain specially-crafted inputs (well, not too special - the naive quicksort hits O(n2) if passed an already-sorted list).
So, even though quicksort is same as any other sort in the worst case, the fact that it almost always achieves substantially better than that justifies calling it a lower run-time class.
qbg wrote:Merge sort and heapsort have worse cases of O(n*log(n))
Xanthir wrote: .... you can say that the average (or amortized) complexity of an insert is O(ln(n))
Also, it's easy to either adapt Quicksort so that it changes when the worst-case behavior occurs so that already-sorted arrays are also n*log n and you need much more special inputs to trigger the worst case (look up median-of-three quicksort or something like that), or truely runs in n*log n worst-case time (though probably with a large constant that doesn't make it worth it).0xBADFEED wrote:qbg wrote:Merge sort and heapsort have worse cases of O(n*log(n))
But implementation issues and stability concerns can make quicksort implementations faster and more desirable in practice. However, merge-sort is often better depending on the datastructure to be sorted. For instance, sorting a linked-list is more natural using merge-sort than quicksort.
Users browsing this forum: No registered users and 1 guest