C # Fast sorting by Sorting Algorithm

Source: Internet
Author: User

Quick sorting: Copy codeThe Code is as follows: namespace QuickSort
{
Class QuickSort
{
Public static void Sort (int [] array)
{
DoSort (array, 0, array. Length-1 );
}
Private static void DoSort (int [] array, int start, int end)
{
If (start <end)
{
Int temp = Partition (array, start, end );
DoSort (array, start, temp-1 );
DoSort (array, temp + 1, end );
}
}
Private static int Partition (int [] array, int start, int end)
{
Int index = start-1;
For (var I = start; I <end; I ++)
{
If (array [I] <array [end])
{
Index ++;
Swap (array, index, I );
}
}
Swap (array, index + 1, end );
Return index + 1;
}
Private static void Swap (int [] array, int index1, int index2)
{
Var temp = array [index1];
Array [index1] = array [index2];
Array [index2] = temp;
}
}
}

The above is the code for fast sorting. There are two important methods:
1. Partition: This method divides an array into three areas by taking an element of an array as a reference element (axis element or main element:
[<= Reference element] [Reference element] [> = reference element]
2. DoSort: This method will call Partition to Partition the array, and recursively call the new Child array to achieve the goal of order.
The code above uses the last element of the array as the reference element, which is only one of the methods for selecting the reference element. We can also select an array element or an element in the middle of the array as a reference element. In fact, the selection of reference elements has a great impact on the performance of quick sorting. If the selected reference element can divide the array into relatively balanced areas, fast sorting will become the fastest sorting algorithm. However, in another extreme situation, each split array is in the relationship between 1 and n-1, and the fast sorting will become very slow. The specific performance data will be discussed later.

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.