Thread: Quick Sort explanation.

1. Member
Join Date
Jan 2009
Posts
21
Rep Power
0

Quick Sort explanation.

Hi guys. I am trying to understand the following code. This isnt an assignment, I am just trying to understand this program. It implements the quick sort method. But I find the code slightly confusing. Could you help me understand it a bit better? Some things I am not clear on:

1. Why do they have that return statement in the quickSort() method
2. What are those two inner while loops doing?
3. What is the code in the brackets doing. quickSort(a, lo == low ? lo+1 : lo, n);

Thanks.
Here is the code:

Java Code:
```class Quick

{

public static void main(String[] args)
{

int [] a = {3,4,1,2,5, 9, 6};
int i;

quickSort(a, 0, a.length - 1);

for(i = 0; i <a.length; i++)
{System.out.println(a[i]);}

}//main

public static void quickSort(int a[], int low, int n)

{

int lo = low;
int hi = n;

if (lo >= n) {
return;
}

int mid = a[(lo + hi)/2];

while (lo < hi)

{

while (lo < hi && a[lo] < mid)
{
lo ++;

}//end inner while

while (lo < hi && a[hi] > mid)
{

hi --;
}//end inner while

if (lo < hi)
{
int temp = a[lo];
a[lo] = a[hi];
a[hi] = temp;

}//end if

}//end outer while

if (hi < lo) {
int temp = hi;
hi = lo;
lo = temp;
}

quickSort(a, low, lo);
quickSort(a, lo == low ? lo+1 : lo, n);

}//end method

}//class```

2. Originally Posted by hawaiifiver
1. Why do they have that return statement in the quickSort() method
return statement use simply to exit the code. In this case is used to exit from the method.

Originally Posted by hawaiifiver
2. What are those two inner while loops doing?
Better to take a piece of paper and write the logic on it and see.

Originally Posted by hawaiifiver
3. What is the code in the brackets doing. quickSort(a, lo == low ? lo+1 : lo, n);
This is about ternary operator. Much similar to the if-else condition.

Java Code:
`lo == low ? lo+1 : lo`
You can right the same logic using if-else as follows.

Java Code:
```if(lo == low) {
[I]select [B]lo + 1[/B][/I]
}
else {
[I]select [B]lo[/B][/I]
}```

3. Member
Join Date
Jan 2009
Posts
21
Rep Power
0
ah cool. i thought those inner while loops were searching the array.

4. Senior Member
Join Date
Sep 2008
Posts
564
Rep Power
6
a better thing to do would be search out pseudocode for quick sort (i'd imagine wikipedia would have some) and then compare them. while it can be a good trait to be able to read code and decipher what it's doing, a more descriptive version might be more useful to you.

funny, i tried googling and everything is rejected as 'looking similar to automated requests from a virus'.

5. Yes, best way to read codes is, looking at the pseudo code or the logic of it rather working on each line of code straightly.

Posting Permissions

• You may not post new threads
• You may not post replies
• You may not post attachments
• You may not edit your posts
•