Quick Sort
Microsoft .NET Framework, ASP.NET, Visual C# (CSharp, C Sharp, C-Sharp) Developer Training, Visual Studio
| CSharp-Online.NET:Articles |
| C# Articles |
| edit |
The quick sort is an in-place, divide-and-conquer, massively recursive sort. As a normal person would say, it's essentially a faster in-place version of the merge sort. The quick sort algorithm is simple in theory, but very difficult to put into code.
The recursive algorithm consists of four steps:
- If there are one or less elements in the array to be sorted, return immediately.
- Pick an element in the array to serve as a "pivot" point. (Usually the left-most element in the array is used.)
- Split the array into two parts - one with elements larger than the pivot and the other with elements smaller than the pivot.
- Recursively repeat the algorithm for both halves of the original array.
The quick sort is by far the fastest of the common sorting algorithms. It is possible to write a special-purpose sorting algorithm that can beat the quick sort for some data sets, but for general-case sorting there isn't anything faster.
The quick sort is recursive, which can make it a bad choice for applications that run on machines with limited memory.
[edit]
Quick Sort Routine Code
// array of integers to hold values private int[] a = new int[100]; // number of elements in array private int x; // Quick Sort Algorithm public void sortArray() { q_sort( 0, x-1 ); } public void q_sort( int left, int right ) { int pivot, l_hold, r_hold; l_hold = left; r_hold = right; pivot = a[left]; while( left < right ) { while( (a[right] >= pivot) && (left < right) ) { right--; } if( left != right ) { a[left] = a[right]; left++; } while( (a[left] <= pivot) && (left < right) ) { left++; } if( left != right ) { a[right] = a[left]; right--; } } a[left] = pivot; pivot = left; left = l_hold; right = r_hold; if( left < pivot ) { q_sort( left, pivot-1 ); } if( right > pivot ) { q_sort( pivot+1, right ); } }
|

