I am trying to understand a quicksort example. I randomly generate 9 numbers and place in a list. The program selects a random pivot. Based on the pivot, the other values in the list are placed into the left list or right list. Then I call the method again using left list and right. This is where I get confused. It doesn't completely sort the 9 numbers. What am I doing wrong?
Here is my updated code. Now, if a pivot number is the same as another number in the list, it is not included in the sorted list when return e.g. unsorted 487878146, sorted 14678 The piece of code that I think is causing the issue is (if (j == pivot) continue;)
public static List<int> QuickSort(List<int> arr)
{
Random random = new Random();
int i, pivot;
List<int> leftList = new List<int>();
List<int> rightList = new List<int>();
if (arr.Count > 1)
{
//pivot = random.Next(arr[0],arr[arr.Count - 1]);
pivot = arr[random.Next(0, arr.Count - 1)];
foreach(int j in arr)
{
if (j == pivot) continue;
if (j <= pivot)
leftList.Add(j);
else
rightList.Add(j);
}
List<int> sortedLeft = QuickSort(leftList);
List<int> sortedRight = QuickSort(rightList);
List<int> tempList = new List<int>();
tempList.AddRange(sortedLeft);
tempList.Add(pivot);
tempList.AddRange(sortedRight);
//for (i = 1; i <= leftList.Count; i++)
// tempList.Add(leftList[i - 1]);
//tempList.Add(pivot);
//for (i = 1; i <= rightList.Count; i++)
// tempList.Add(rightList[i - 1]);
return tempList;
}
return arr;
}
Randomobjects. Create one and reuse it. Though here it is probably not related to your actual problem.