Compare sorting algorithms' performance: Difference between revisions

m
Line 1,705:
<lang Mathematica>ClearAll[BubbleSort,ShellSort]
BubbleSort[in_List]:=Module[{x=in,l=Length[in],swapped},swapped=True;
While[swapped,swapped=False;
Do[If[x[[i]]>x[[i+1]],x[[{i,i+1}]]//=Reverse;
swapped=True;],{i,l-1}];];
x]
ShellSort[lst_]:=Module[{list=lst,incr,temp,i,j},incr=Round[Length[list]/2];
While[incr>0,For[i=incr+1,i<=Length[list],i++,temp=list[[i]];j=i;
While[(j>=(incr+1))&&(list[[j-incr]]>temp),list[[j]]=list[[j-incr]];j=j-incr;];
list[[j]]=temp;];
If[incr==2,incr=1,incr=Round[incr/2.2]]];list]
]
 
times=Table[
arr=ConstantArray[1,n];
t1={{n,AbsoluteTiming[BubbleSort[arr];][[1]]},{n,AbsoluteTiming[ShellSort[arr];][[1]]}};
arr=Sort[RandomInteger[{10^6},n]];
t2={{n,AbsoluteTiming[BubbleSort[arr];][[1]]},{n,AbsoluteTiming[ShellSort[arr];][[1]]}};
arr=RandomInteger[{10^6},n];
t3={{n,AbsoluteTiming[BubbleSort[arr];][[1]]},{n,AbsoluteTiming[ShellSort[arr];][[1]]}};
{t1,t2,t3}
,
{n,2^Range[13]}
];
 
1,111

edits