C # implement all classical sorting algorithms

Source: Internet
Author: User

1. Select sorting

Select sort
Class SelectionSorter
{
Private int min;
Public void Sort (int [] arr)
{
For (int I = 0; I <arr. Length-1; ++ I)
{
Min = I;
For (int j = I + 1; j <arr. Length; ++ j)
{
If (arr [j] <arr [min])
Min = j;
}
Int t = arr [min];
Arr [min] = arr [I];
Arr [I] = t;
}
}
Static void Main (string [] args)
{
Int [] array = new int [] {1, 5, 3, 6, 10, 55, 9, 2, 87, 12, 34, 75, 33, 47 };
SelectionSorter s = new SelectionSorter ();
S. Sort (array );
Foreach (int m in array)
Console. WriteLine ("{0}", m );
}
}

2. Bubble Sorting

Bubble Sorting
Class EbullitionSorter
{
Public void Sort (int [] arr)
{
Int I, j, temp;
Bool done = false;
J = 1;
While (j <arr. Length )&&(! Done) // determine the length
{
Done = true;
For (I = 0; I <arr. Length-j; I ++)
{
If (arr [I]> arr [I + 1])
{
Done = false;
Temp = arr [I];
Arr [I] = arr [I + 1]; // exchange data
Arr [I + 1] = temp;
}
}
J ++;
}
}

Static void Main (string [] args)
{
Int [] array = new int [] {1, 5, 3, 6, 10, 55, 9, 2, 87, 12, 34, 75, 33, 47 };
EbullitionSorter e = new EbullitionSorter ();
E. Sort (array );
Foreach (int m in array)
Console. WriteLine ("{0}", m );

}
}

3. Fast sorting

Quick sorting
Class QuickSorter
{
Private void swap (ref int l, ref int r)
{
Int temp;
Temp = l;
L = r;
R = temp;
}
Public void Sort (int [] list, int low, int high)
{
Int pivot; // storage pivot
Int l, r;
Int mid;
If (high <= low)
Return;
Else if (high = low + 1)
{
If (list [low]> list [high])
Swap (ref list [low], ref list [high]);
Return;
}
Mid = (low + high)> 1;
Vertex = list [mid];
Swap (ref list [low], ref list [mid]);
L = low + 1;
R = high;
Do
{
While (l <= r

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.