A detailed description of the C # Classic sorting algorithm (above)

Source: Internet
Author: User
This article mainly for you in detail the C # Seven classic sorting algorithm series on the chapter, bubble sort, fast sorting, etc., with a certain reference value, interested in small partners can refer to

Today is the beginning, you have to blow the algorithm, the algorithm is like a sword in the development of the program, where the knife starts to fall.

To solve the problem of sorting in reality, the algorithm has seven swords that can help you ma DAO success.

The first sort is divided into four types:

Exchange sort: Includes bubble sort, quick sort.

Select Sort: Includes direct selection sorting, heap sorting.

Insert Sort: Includes direct insert sort, hill sort.

Merge sort: merge sort.

So what we're talking about today is the swap sort, and we all know that the C # class library provides the sort of a quick row, in order to make today's fun point,

We design algorithms to match the fast-running contests offered by the class library. Fight for KO opponents.

Bubble Sort:

Let's start by designing our own "bubble sort", a realistic example of this sort:

I grabbed a handful of sand still in the water, then the sand will immediately sink into the bottom of the sand, the dust will temporarily sink into the bottom of the water, but will immediately like bubbles surfaced, and finally the truth.

On the idea of bubbling, I would not say the official theory, nor the words to put it, my mind is to look at the picture to speak.

So we just.

To achieve the bubbling effect, we are going to put a set of numbers up to see, we think, how to bubble? How to realize the heavy sink, the light float?

The first step: we take 40 and 20 ratio, found that 40 is the eldest, do not exchange.

The second step: then push forward one step, is to take 20 and 30 ratio, found that 30 is the eldest, will exchange.

The third step: Take the exchange after the 20 and 10 ratio, found himself is the eldest, do not exchange.

Fourth step: Take 10 with 50 exchange, found that 50 is the eldest, to exchange.

Finally, we go through a traversal to send the smallest number in the array, and see, we've taken another step towards the goal.

Now everyone is aware of the idea, the following we are strongly asked to fight with the fast platoon, either you die or I live.


Using system;using system.collections.generic;using system.linq;using system.text;using System.Diagnostics;using System.threading;namespace bubblesort{public class Program {static void Main (string[] args) {//five times comparison F        or (int i = 1; I <= 5; i++) {list<int> List = new list<int> ();          Insert 2k random number into array for (int j = 0; J <; J + +) {Thread.Sleep (1); List. ADD (New Random ((int) DateTime.Now.Ticks).        Next (0, 100000));        } Console.WriteLine ("\ n" + i + "Times comparison:");        Stopwatch watch = new Stopwatch (); Watch.        Start (); var result = list. (single = single).        ToList (); Watch.        Stop (); Console.WriteLine ("\ n Quick sort time consuming:" + watch.)        Elapsedmilliseconds); Console.WriteLine ("10 Numbers before output:" + string.) Join (",", result.) Take (10).        ToList ())); Watch.        Start ();        result = Bubblesort (list); Watch.        Stop (); Console.WriteLine ("\ n bubble sort time consuming:" + watch.)   Elapsedmilliseconds);     Console.WriteLine ("10 Numbers before output:" + string.) Join (",", result.) Take (10).      ToList ()));      }}//bubble sort algorithm static list<int> Bubblesort (list<int> List) {int temp; First loop: Indicates the number of times to compare, such as the number of list.count, must be compared count-1 times for (int i = 0; i < list. Count-1;        i++) {//list.count-1: Take the last number of data subscript,//j>i: From the back to the next subscript must be greater than the previous subscript, or beyond. for (int j = list. Count-1; J > i; j--) {//If the previous number is greater than the next number, swap if (list[j-1] > List[j]) {temp = List[j-1]            ;            LIST[J-1] = List[j];          LIST[J] = temp;    }}} return list; }  }}

Whining, looking at these two sort of medical report, the heart is cold, bubble was fast row Ko, really miserable, no wonder people say bubble efficiency low, originally really low.

Quick sort:

Since can bubble Ko off, immediately aroused our interest, TND quick Platoon Why so fast, must study well.

First of all:

We can see:

Left pointer, right pointer, base reference number.

In fact, the idea is quite simple, that is, through the first traversal (let left and right pointer coincident) to find the array of cutting points.

First step: First we remove the number (20) from the left position of the array as the base reference.

The second step: looking forward from the right position of the array, always finding a smaller number than (base),

If found, assign this number to the left position (that is, assign 10 to 20),

At this point the array is: 10,40,50,10,60,

The left and right pointers are 10, respectively, before and after.

Step three: Look backwards from the left position of the array, always finding a larger number than (base),

If found, assigns this number to the position of right (that is, 40 assigns to 10),

At this point the array is: 10,40,50,40,60,

The left and right pointers are 40, respectively, before and after.

Fourth step: Repeat the "second, third" step until the left and right pointers coincide,

Finally, insert (base) into the 40 position,

At this point the array value is: 10,20,50,40,60, which completes the sort once.

Fifth step: At this point 20 has been infiltrated into the interior of the array, 20 of the left of a group of 20 small, 20 of the right side as a group of numbers are greater than 20,

Take 20 as the entry point to the left and right sides according to the "first, second, third, fourth" step, the final quick Platoon is done.

Similarly, we compare our own design with the quick shot provided by the class library.


Using system;using system.collections.generic;using system.linq;using system.text;using System.Threading;using      System.diagnostics;namespace quicksort{public class Program {static void Main (string[] args) {//5 times Comparison        for (int i = 1; I <= 5; i++) {list<int> List = new list<int> ();          Insert 200 random numbers into the array for (int j = 0; J < x; j + +) {Thread.Sleep (1); List. ADD (New Random ((int) DateTime.Now.Ticks).        Next (0, 10000));        } Console.WriteLine ("\ n" + i + "Times comparison:");        Stopwatch watch = new Stopwatch (); Watch.        Start (); var result = list. (single = single).        ToList (); Watch.        Stop (); Console.WriteLine ("\ nthe system-defined quick sort takes time:" + watch.)        Elapsedmilliseconds); Console.WriteLine ("10 Numbers before output:" + string.) Join (",", result.) Take (10).        ToList ())); Watch.        Start (); New Quicksortclass (). QuickSort (list, 0, list.        COUNT-1); Watch.        Stop (); Console.WriteLine ("\ n I write my own quick sort of consumptionFee Time: "+ watch.        Elapsedmilliseconds); Console.WriteLine ("10 Numbers before output:" + string.) Join (",", list. Take (10).      ToList ())); }}} public class Quicksortclass {///<summary>///split function///</summary>///<param name= "list" > Pending order Array </param>///<param name= "left" > Array's subscript </param>///<param name= "right" ></param>///      <returns></returns> public int pision (list<int> List, int. left, int right) {//First select a Datum element      int basenum = List[left]; while (left < right) {//start looking forward from the end of the array, and always find a number smaller than base (including base equivalent) while (back < R && Li        St[right] >= basenum) right = right-1;        Finally found a smaller element than Basenum, the thing to do is to place this element in base position list[left] = List[right]; Search backwards from the left side of the array, always find the number larger than base (including base equivalent) while (left < right && List[left] <= basenum)        = left + 1;      Finally found a larger than basenum elements, to do is to put this element in the final position list[right] = List[left]; }//Lastis to put the basenum in the left position list[left] = Basenum;    Finally, we found that the left side of the value of the lower part of a small, the right side of the leftmost position is greater//At this point, we completed the first sort of return left; The public void QuickSort (list<int> List, int left, int right) {///subscript must be less than the subscript below, otherwise it will go beyond the IF (Ieft < rig        HT) {//array to split, take out the next segmented datum designator int i = pision (list, left, right);        A set of values on the left side of the Datum label is cut recursively so that the values are sorted QuickSort (list, left, i-1);      A set of values on the right side of the Datum label is cut recursively so that the values are sorted QuickSort (list, i + 1, OK); }    }  }}

Yes, fast-line is fast, no wonder the inside of the library to use him as a sort of standard.

Well, finally share the following:

Bubbling time Complexity:0 (N)-0 (n^2)

The time complexity of the fast line is:

Average complexity:N (LOGN)

Worst-Case Complexity: 0 (n^2)

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.