Created
July 6, 2012 00:25
-
-
Save kflu/3057291 to your computer and use it in GitHub Desktop.
Quick Sort in C#
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| using System; | |
| using System.Collections.Generic; | |
| namespace ConsoleApplication14 | |
| { | |
| class Program | |
| { | |
| static void Main(string[] args) | |
| { | |
| var A = new int[] { 4, 3, 5, 2 }; | |
| var sorter = new QSort<int>(A); | |
| sorter.Sort(); | |
| foreach (var i in sorter.A) | |
| Console.WriteLine(i); | |
| Console.Read(); | |
| } | |
| } | |
| class QSort<T> where T:IComparable | |
| { | |
| public IList<T> A; | |
| public QSort(IList<T> A) | |
| { | |
| this.A = A; | |
| } | |
| public int Partition(int L, int U) | |
| { | |
| int s = U; | |
| int p = L; | |
| while (s != p) | |
| { | |
| if (A[p].CompareTo(A[s]) <= 0) | |
| { | |
| p++; | |
| } | |
| else | |
| { | |
| Swap(p, s); | |
| Swap(p, s - 1); | |
| s--; | |
| } | |
| } | |
| return p; | |
| } | |
| private void Swap(int p, int s) | |
| { | |
| T tmp = A[p]; | |
| A[p] = A[s]; | |
| A[s] = tmp; | |
| } | |
| public void Sort(int L, int U) | |
| { | |
| if (L >= U) return; | |
| int p = Partition(L, U); | |
| Sort(L, p-1); | |
| Sort(p+1, U); | |
| } | |
| public void Sort() | |
| { | |
| Sort(0, A.Count - 1); | |
| } | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment