CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com

# Thread: QuickSort Algorithm just for a exercise

1. Junior Member
Join Date
Jun 2004
Location
UK
Posts
1

## QuickSort Algorithm just for a exercise

Just tried creating a quick sort algorithm in c# to sort an array of integers - from a long distant memory.

Yes I could of just used the in built quicksort or better still just copied and pasted somebody elses off google.. But anyway, I have noticed at times will not sort the list entirely..

Just wondered where the problem is exactly?

Please bare in mind that it has been a long time since I wrote code, so dont be too brutal lol.

Code:
```        static public int[] quickSort(int[] sortArray, int left, int right)
{
// if there are less than 2 elements in array or comparison no need to sort
if ((sortArray.Length < 2) || ((right-left) < 2))
{
return sortArray;
}

// set random number for pivot
Random rand = new Random();
int pivotIndex = rand.Next(left, right);

int l = left, r = right;

while (l < r)
{
//leave data that is already in good in relation to index
while (sortArray[l] < sortArray[pivotIndex])
{
l++;
}
while (sortArray[r] > sortArray[pivotIndex])
{
r--;
}

// swap elements
if (sortArray[l] >= sortArray[r])
{

int temp = sortArray[l];
sortArray[l] = sortArray[r];
sortArray[r] = temp;

//continue to seek
l++;
r--;
}
}

// recursive call to sort either side of pivot
quickSort(sortArray, left, pivotIndex);
quickSort(sortArray, pivotIndex, right);

return sortArray;

}```

2. Member +
Join Date
Jan 2009
Posts
596

## Re: QuickSort Algorithm just for a exercise

Code:
```        static public int[] quickSort(int[] sortArray, int left, int right)
{
// if there are less than 2 elements in array or comparison no need to sort
if ((sortArray.Length < 2) || ((right-left) < 2))
{
return sortArray;
}
// rest of code...
}```
Suppose you call this on a two element array, so left == 0 and right == 1. Then (right-left) == 1, i.e. is less than 2. Your code will just return in this case without sorting the 2 elements.

#### Posting Permissions

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

Click Here to Expand Forum to Full Width