**I need to make a quicksort algorithm but so that it uses only one list and does swaps inside of it. I managed to make it “sort” or position the first element but now i don’t know how to implement the recursion. The biggest problem I’m having is how to recursively work on a part of the list instead of making the new one. Here is my code: ——————————————————————————-** New code, same problem.
Here is my code. It does the job but gets stuck in the loop.
JavaScript
x
25
25
1
def qsort(n,l,g):
2
if l is None:
3
l=0
4
if g is None:
5
g=len(n)
6
if g-l<=1:
7
return n
8
print g-l
9
p=n[l]
10
i=1+l
11
j=1+l
12
for x in n[l+1:g]:
13
if x<p:
14
n[i],n[j]=n[j],n[i]
15
i+=1
16
j+=1
17
n[l],n[i-1]=n[i-1],n[l]
18
ls=0
19
le=i-1
20
gs=i
21
ge=j
22
print n
23
qsort(n,ls,le)
24
qsort(n,gs,ge)
25
Can someone give me any suggestions, I’m lost. Can’t find whats wrong or how to fix it. Know its messy but cant do better atm :D
Advertisement
Answer
Write it like this:
JavaScript
1
11
11
1
def qsort(li, lo=None, hi=None):
2
if lo is None:
3
lo = 0
4
if hi is None:
5
hi = len(li) - 1
6
7
8
if hi - lo > 1:
9
qsort(## left half ##)
10
qsort(## right half ##)
11
lo
and hi
are the smallest and largest indexes you should look at in li
, respectively.