MathGroup Archive 2010

[Date Index] [Thread Index] [Author Index]

Search the Archive

whats wrong with this code ?!

  • To: mathgroup at smc.vnet.net
  • Subject: [mg110456] whats wrong with this code ?!
  • From: "becko" <becko565 at hotmail.com>
  • Date: Sat, 19 Jun 2010 07:47:54 -0400 (EDT)

ok. I give up. I've been struggling with this the entire night. I have 
three functions: swap[..], split[..] and qksort[..]. The objective is to 
implement a recursive sort algorithm. I have tried to execute it on 
list={2,5,4,7,9,1};. But I keep getting the "Cannot take positions .. 
through .. in .." message. You may need to execute it a few times to see 
the error (because of it depends on the RandomInteger). Here are the 
three functions. Thanks in advance.

swap[x_List,i_Integer,j_Integer]:=ReplacePart[x,{i->x[[j]],j->x[[i]]}]

slowsort[x_List]:=
Module[{z=x},
Do[
If[z[[j]]<z[[r]],z=swap[z,j,r]],
{r,1,Length[z]-1},{j,r+1,Length[z]}
];
z
]

split[x_List,left_Integer,right_Integer]:=
Module[{L=RandomInteger[{left,right}],z,T,i=left},
 T=x[[L]];z=swap[x,left,L];
Do[
If [ z[[j]]<T,z=swap[z,++i,j] ],
{j,left+1,right}
];
z=swap[z,left,i];
{i,z}
]

qksort[x_List,left_Integer,right_Integer]:=
If[right-left>=1,
Module[{i,z},
{i,z}=split[x,left,right];
{qksort[z,left,i-1][[left;;i-1]],z[[i]],qksort[z,i+1,right][[i+1;;right]]}//Flatten
],
x
]


  • Prev by Date: Re: how to scale text to a bounding rectangle?
  • Next by Date: An optimization problem
  • Previous by thread: Re: NotebookDirectory for package (.m) files?
  • Next by thread: Re: whats wrong with this code ?!