Quick Sort code

Source: Internet
Author: User

Using System;
Using System. Collections. Generic;
Using System. Text;
Namespace temp
{
Public class QuickSort
{
/// <Summary>
/// Sort
/// </Summary>
/// <Param name = "numbers"> array to be sorted </param>
/// <Param name = "left"> Index of the first element in the array </param>
/// <Param name = "right"> Index of the last element in the array </param>
Private static void Sort (int [] numbers, int left, int right)
{
// If the left index is smaller than the right index, the sorting is not completed.
If (left <right)
{
// Take the middle element as the comparison benchmark. If the value is smaller than the value, it moves to the left and greater than the value to the right.
Int middle = numbers [(left + right)/2];
Int I = left-1;
Int j = right + 1;
While (true)
{
While (numbers [++ I] <middle & I <right)
{;}
While (numbers [-- j]> middle & j> 0)
{;}
If (I> = j) break;
Swap (numbers, I, j );
}
Sort (numbers, left, I-1 );
Sort (numbers, j + 1, right );
}
}
/// <Summary>
/// Exchange element values
/// </Summary>
/// <Param name = "numbers"> array </param>
/// <Param name = "I"> current left index </param>
/// <Param name = "j"> current right index </param>
Private static void Swap (int [] numbers, int I, int j)
{
Int number = numbers [I];
Numbers [I] = numbers [j];
Numbers [j] = number;
}
Public static void Main ()
{
Int [] arr = {6, 5, 2, 9, 7, 4, 0,-1,-4,-2, 2, 0, 9 };
Sort (arr, 0, arr. Length-1 );
StringBuilder temp = new StringBuilder ();
For (int I = 0; I <= arr. Length-1; I ++)
{
Temp. Append (arr [I]. ToString () + ",");
}
Console. WriteLine (temp. ToString (). Substring (0, temp. Length-1 ));
Console. ReadLine ();
}
}
}

 
Author Zhang Yin

Related Article

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.