Algorithm
Running time:
A algorithm's running time depends on a lot of things,such as:
-
Input itself.If the input is already sorted,then the algorithm may have very little work to do.
-
Size of the input.Some algorithms are better at sorting small data while some others are better at large data.
Normally,we make the size of the input a param "n" and "T(n)" represents the "time"(not a real time) so that it is much easier to analysis the performance of this Algorithm.
Kinds of analysis:
-
Worst case(usually). The max time of any input of size n.
-
Average case(sometime). Expected time over all inputs of size n.
- Expected time. It's the time of every input times the probability that it will be that input.
-
Best case(bogus). The min time of any input of size n.
A algorithm's performance will never depend on how it work out things with a suitable inputs.
Some Codes(write by myself, don't judge):
Merge sort in Javascript .
1 function merge(arr1,arr2,c)//leave "c" alone. 2 { 3 var a = arr1[0]; 4 var b = arr2[0]; 5 if(c == null) 6 c = []; 7 if(a == undefined && b == undefined) 8 return c; 9 if(b == undefined || a <= b) 10 c.push(arr1.shift()); 11 else if(a == undefined || a > b) 12 c.push(arr2.shift()); 13 return merge(arr1,arr2,c); 14 } 15 16 function merge_sort(a) 17 { 18 var len = a.length; 19 if(len == 1) 20 { 21 return a; 22 } 23 var b = a.splice(parseInt(len/2)); 24 var c = merge_sort(a); 25 var d = merge_sort(b); 26 return merge(c,d); 27 } 28 29 var res = merge_sort(a);