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; }


Reply With Quote

Bookmarks