Four simple sorting algorithms

Source: Internet
Author: User

I think if you want to be a good developer, not only to actively learn the popular new technologies, such as WCF, ASP. NET MVC, Ajax, etc., skilled in the use of some of the more mature technology, such as ASP. NET, WinForm. There should also be solid computer fundamentals, such as data structures, operating systems, compiling principles, networking and data communications. Some friends may feel that this aspect of things too difficult and theoretical, prohibitive, but I think the holiday spent an afternoon time, research an algorithm or a data structure, and then write the experience, is not a pleasure? So, I'm going to summarize some of the common data structures and algorithms, not necessarily to focus a period of time to spend a lot of energy, but in a relatively idle time with a very relaxed attitude to complete. The last thing I want to do is turn blogging or learning technology into a job or a burden, and think of it as a pastime in life. People always say persistence is not easy, in fact, when you mention "stick" two words, you have seen this matter as a pain, your heart is not willing to do this thing, so you need to insist. You never heard people say, "I insisted on playing 10 years of video games", or "stick to the ten years of animation, film," insisted and the beloved girlfriend spent ten years? I never insisted, because I regard it as a hobby and pastime, just as many people play online games.

Well, gossip says so much, let's get back to the chase. Because this is a lot of work, so here only give a simple description and implementation, for my own and interested friends reference. I will try to do it in C # and C + + two languages, and for some structures that are not well-represented in C #, they are only implemented in C + +.

This article will describe the four simplest sorting methods, insert sort, bubble sort, select Sort, and Hill sort, which I call "simple sorting" here because they are simpler than quick sort, merge sort, heap sort, assign sort, cardinality sort from understanding and algorithm. For these sorts of things, I'll call them "advanced sort."

Simple sorting

Before you begin, declare a convention that, for the data saved in the array, is called a record to avoid confusion with names such as "element", "object", and so on. For a record, the code used for sorting is called the key code . Obviously, the selection of the key code is closely related to the type of record in the array, and if the record is an int value, the key code is itself; If the record is a custom object and it is likely to contain more than one field, selecting one of these fields is the key code. The algorithm for sorting and finding is related to the size of two records, and how to determine the size of two objects should be determined by the client (client object) of the algorithm program. For. NET, we can create a class that implements the Icomparer<t> (which is similar for C + +). For more information about icomparer<t>, refer to this article, "Sorting based on business objects". Finally, in order to make the program simple, I did not deal with the empty array.

1. Insert Sorting algorithm idea

Insert sort uses a two-layer nested loop to process the records to be sorted one by one. Each record is compared to a sequence of records that has been ordered earlier and inserted into the appropriate position. Assuming that the array length is n, the outer loop control variable i is sequentially progressive from 1 to n-1, which is used to select which record is currently being processed; the inner loop control variable J, the initial value is I, and is reduced from I to 1, in contrast to the previous record, determines which position to insert the element into. The key idea here is that the previous i-1 record is already in order when working with article I records. It is important to note that because the current record is compared to the previous record, the loop control variable starts with a value of 1 (array subscript), and if 0, the previous record is-1, the array is out of bounds.

Now let's examine the processing of the records of article I: Assuming that the outer loop is progressive to the first record, and the value of the key code is x, then there are two possible situations:

    1. If the previous record is larger than x, then swap them until the key code of the previous record is smaller or equal than X.
    2. If the previous record is smaller or equal than X, all previous records must be ordered and smaller than X, at which point the inner loop exits. The outer loop moves forward, processing the next record.
Algorithm implementation (C #)

public class Sortalgorithm {
Insert Sort
public static void Insertsort<t, c> (t[] array, C comparer)
where c:icomparer<t>
{
for (int i = 1; I <= array. Length-1; i++) {
Console.Write ("{0}:", i);
int j = i;
while (J>=1 && comparer.compare (Array[j], array[j-1]) < 0) {
Swap (ref array[j], ref array[j-1]);
j--;
}
Console.WriteLine ();
Algorithmhelper.printarray (array);
}
}

Swaps the first and second elements of an array of arrays and the first J elements
private static void swap<t> (ref t x,ref t y) {
Console.Write ("{0}<-->{1}", X, y);
T temp = x;
x = y;
y = temp;
}
}

The Console.WriteLine () method above and the Algorithmhelper.printarray () method are simply for testing convenience, and the PrintArray () method prints the contents of the array sequentially. The Swap<t> () method is used to swap two records in an array, and the number of interchanges is printed (I commented out here, but I can uncomment them when testing). The outer for loop control variable I represents the current processing of article I records.

public class Algorithmhelper {
Print array Contents
public static void Printarray<t> (t[] array) {
Console.Write ("Array:");
foreach (T item in array) {
Console.Write ("{0}", item);
}
Console.WriteLine ();
}
}

Get comparer, compare
public class Comparerfactory {
public static icomparer<int> Getintcomparer () {
return new Intcomparer ();
}

public class Intcomparer:icomparer<int> {
public int Compare (int x, int y) {
return X.compareto (y);
}
}
}

Above this code we create a Comparerfactory class, which is used to obtain a Intcomparer object that implements the Icomparer<t> interface, which specifies the rules for comparing size between key codes of two int types. If you have a custom type, such as MyType, just add another class in comparerfactory, such as Mytypecomparer, and then let the class also implement the Icomparer<t> interface. Finally, add a method to return Mytypecomparer.

Output demo (C #)

Next we look at the client code and output:

static void Main (string[] args) {
Int[] array = {42,20,17,13,28,14,23,15};
Int[] Array = {9, 8, 7, 6, 5, 4, 3, 2, 1, 0};
Algorithmhelper.printarray (array);

Sortalgorithm.insertsort
(Array, Comparerfactory.getintcomparer ());
}

Algorithm implementation (c + +)

Sort the int type
Class intcomparer{
Public
static bool Smaller (int x, int y) {
Return x<y;
}
static bool Equal (int x, int y) {
return x==y;
}
static bool Larger (int x, int y) {
Return x>y;
}
};

Insert Sort
Template <class T, class c>
void Insertsort (T a[], int length) {
for (int i=1;i<=length-1;i++) {
int j = i;
while (J>=1 && C::smaller (A[j], a[j-1])) {
Swap (A[j], a[j-1]);
j--;
}
}
}

2. Bubble Sorting algorithm idea

If you have never learned about algorithmic knowledge and need to design an algorithm for array sorting, it is likely that the bubble sorting algorithm is designed. Because it is well understood, it is easy to implement. It also contains two layers of loops, assuming that the array length is n, the outer loop control variable i from 0 to n-2 increment, this outer loop is not processing a record, just control the comparison of the number of trips, from 0 to n-2, altogether compared n-1. Why do N records only need to compare n-1 trips? We can start by looking at the simplest two-digit sort: like 4 and 3, we can get 3, 4 if we compare one trip. For more records you can do the analogy.

The exchange of the array records is done by the inner loop, the control variable J initial value is n-1 (array subscript), has been decremented to 1. The array record starts at the end of the array and, if the previous record is larger than the key code of the current record, is exchanged until the current record has a subscript of 1 (the subscript for the previous record is 0), compared to the previous record. The whole process is like a bubble rising from the bottom, and the sorting algorithm is named to bubble sort.

Let's take a look at it, in this sort of way, after the first loop, the smallest must be at the top of the array (subscript 0); After the second loop, the minor record is in the second (subscript 1) position of the array; and so on, after the n-1 cycle, The N-1 small record is located at the location of the array n-1 (subscript n-2). The nth loop is no longer required because the last one is already positioned at the end of the array (subscript n-1).

Algorithm implementation (C #)

Bubble sort
public static void Bubblesort<t, c> (t[] array, C comparer)
where c:icomparer<t>
{
int length = array. Length;

for (int i = 0; I <= length-2; i++) {
Console.Write ("{0}:", i + 1);
for (int j = length-1; J >= 1; j--) {
if (Comparer.compare (Array[j], array[j-1]) < 0) {
Swap (ref array[j], ref array[j-1]);
}
}
Console.WriteLine ();
Algorithmhelper.printarray (array);
}
}

Output demo (C #)

static void Main (string[] args) {
Int[] array = {42,20,17,13,28,14,23,15};
Algorithmhelper.printarray (array);

Sortalgorithm.bubblesort
(Array, Comparerfactory.getintcomparer ());
}

Algorithm implementation (c + +)

Bubble sort
Template <class T, class c>
void Bubblesort (T a[], int length) {
for (int i=0;i<=length-2;i++) {
for (int j=length-1; j>=1; j--) {
if (C::smaller (A[j], a[j-1]))
Swap (A[j], a[j-1]);
}
}
}

3. Choose the idea of sorting algorithms

The selection sort is an improvement on the bubbling sort, as can be seen from the output of the bubbling sort above, in order to have the minimum value of 13 in the first position labeled as 0 by the array at the end of the array bubble, and exchanged several times. For each subsequent trip, a similar exchange will be made.

The idea of sorting is: for the first trip, search the entire array, look for the smallest, and then place in the array of position No. 0; For the second trip, search for the n-1 of the array, find the smallest (smaller for the entire array), and place it in the 1th position of the array. At the first pass, search the array for n-i+1 records, looking for the smallest record (which is small for the entire array), and place it in the position of the array i-1 (note that the array starts with 0). As you can see, the choice of sorting significantly reduces the number of interchanges.

It is important to note that the inner loop does not need to be reduced to 1 in the first pass, as long as the loop is the same as I do, because the previous position must be smaller than it (that is, I small). In addition, the inner loop is j>i, not j>=i, because I was immediately saved to the Lowestindex after entering the loop.

Algorithm implementation (C #)

public static void Selectionsort<t, c> (t[] array, C comparer)
where c:icomparer<t>
{
int length = array. Length;
for (int i = 0; I <= length-2; i++) {
Console.Write ("{0}:", i+1);
int lowestindex = i; Array index of the smallest record
for (int j = length-1; j > i; j--) {
if (Comparer.compare (Array[j], Array[lowestindex]) < 0)
Lowestindex = j;
}
Swap (ref array[i], ref array[lowestindex]);
Algorithmhelper.printarray (array);
}
}

Output demo (C #)

static void Main (string[] args) {
Int[] array = {42,20,17,13,28,14,23,15};
Algorithmhelper.printarray (array);

Sortalgorithm.selectionsort
(Array, Comparerfactory.getintcomparer ());
}

Algorithm implementation (c + +)

Select sort
Template <class T, class c>
void Selectionsort (T a[], int length) {
for (int i = 0; I <= length-2; i++) {
int lowestindex = i;
for (int j = length-1; j>i; j--) {
if (C::smaller (A[j], A[lowestindex]))
Lowestindex = j;
}
Swap (A[i], a[lowestindex]);
}
}

4. Hill sort

Hill sort uses a feature of the insertion sort to optimize the sorting algorithm, which is characterized by the insertion sort: When the array is basically ordered, the insertion sort is more efficient . For example, an array such as the following:

Int[] Array = {1, 0, 2, 3, 5, 4, 8, 6, 7, 9};

The output of the insert sort is as follows:

It can be seen that although the number of comparisons is not reduced, the number of exchanges is significantly less. The general idea of the hill sort is to make the array basically orderly and then apply the insertion sort. The process is as follows: Suppose there is an array of int a[] = {42,20,17,13,28,14,23,15}, without losing its generality, we set its length to long.

The first trip, step step = LENGTH/2 = 4, the array is divided into 4 groups, each group of 2 records, the subscript is (0,4) (1,5) (2,6) (3,7), converted to a number, then {42,28}, {20,14}, {17,23}, {13,15}. Each grouping is then inserted and sorted, followed by {28,42}, {14,20}, {17,23}, {13,15}, and the actual value of the original array becomes {28,14,17,13,42,20,23,15}. It is important to note that the position of the group is recorded in the original array, in the 2nd grouping {14,20}, its subscript is (1,5), so the two records in the original array subscript is a[1]=14;a[5]=20.

The second time, step step = STEP/2 = 2, the array is divided into 2 groups, each group of 4 records, the subscript is (0,2,4,6) (1,3,5,7); Convert to a number, {28,17,42,23}, {14,13,20,15}, and then insert sort for each grouping , get {17,23,28,42}{13,14,15,20}. At this point the array becomes {17,13,23,14,28,15,42,20}, which is basically ordered.

The third time, the step STEP=STEP/2 = 1, at this time quite a complete insertion sort, get the final result {13,14,15,17,20,23,28,42}.

Algorithm implementation (C #)

Hill sort
public static void Shellsort<t, c> (t[] array, C comparer)
where c:icomparer<t>
{
for (int i = array. LENGTH/2; I >= 1; i = I/2) {
Console.Write ("{0}:", i);
for (int j = 0; J < i; J + +) {
Insertsort (Array, J, I, comparer);
}
Console.WriteLine ();
Algorithmhelper.printarray (array);
}
}

Sort Insert Sort by Uchille
private static void Insertsort<t, c>
(t[] array, int startIndex, int step, C comparer)
where c:icomparer<t>
{
for (int i = startIndex + step; I <= array. Length-1; i + = Step) {
int j = i;
while (j>= step && comparer.compare (Array[j], Array[j-step]) <0) {
Swap (ref array[j], ref array[j-step]);
J-= step;
}
}
}

Note that the parameters of the sort Insertsort () method are inserted here, startindex is the starting index of the grouping, step is the step, as you can see, the preceding insertion sort is just a special case of step=1,startindex=0 here .

Output demo (C #)

static void Main (string[] args) {
Int[] array = {42,20,17,13,28,14,23,15};
Algorithmhelper.printarray (array);

Sortalgorithm.shellsort
(Array, Comparerfactory.getintcomparer ());
}

Algorithm implementation (c + +)

Hill sort
Template<class T, Class c>
void Shellsort (T a[], int length) {
for (int i = LENGTH/2; I >= 1; i = I/2) {
for (int j = 0; j<i; j + +) {
Insertsort<t, C> (&a[j], length-1, i);
}
}
}

Sort Insert Sort by Uchille
Template<class T, Class c>
void Insertsort (T a[], int length, int step) {
for (int i = step; i<length; i+= Step) {
int j = i;
while (J>=step && C::smaller (A[j], A[j-step])) {
Swap (A[j], a[j-step]);
J-=step;
}
}
}

For the cost of the above three algorithms, insert sort, bubble sort, select sort, are θ (N2), and Hill sort slightly better, is θ (n1.5), about the algorithm analysis, everyone interested can refer to related books. It is recommended that "data structure and algorithm analysis (c + +) Second Edition" and "algorithm I~iv (c + + implementation)-Basic, data structure, sorting and search" are very good, I mainly refer to these two books.

Thanks for reading, I hope this article can bring you help.

Four simple sorting algorithms

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.