Services & Resources / Wolfram Forums / MathGroup Archive
-----

MathGroup Archive 2010

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

Search the Archive

Re: whats wrong with this code ?!

  • To: mathgroup at smc.vnet.net
  • Subject: [mg110480] Re: whats wrong with this code ?!
  • From: Themis Matsoukas <tmatsoukas at me.com>
  • Date: Sun, 20 Jun 2010 03:46:10 -0400 (EDT)

Get a good night's sleep. Then, fix the line

{
   qksort[z,left,i-1][[left;;i-1]],
   z[[i]],
   qksort[z,i+1,right][[i+1;;right]]
}

If qksort[z,left,i-1] contains fewer elements that i-1, or qksort[z,i+1,right] contains fewer than right, you will get the error message. You may try to debug your qksort using a couple print statements, as in the example below:

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

This will print your lists before picking out their parts, and will also show you which parts are to be picked. 

Themis


On Jun 19, 2010, at 7:47 AM, becko wrote:

> 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: Bar chart style with ListPlot
  • Next by Date: Re: defining a function of functions
  • Previous by thread: whats wrong with this code ?!
  • Next by thread: Re: whats wrong with this code ?!