Four simple sorting algorithms

Source: Internet
Author: User
Document directory
  • 1. Insert sorting
  • 2. Bubble Sorting
  • 3. Select sort
  • 4. Hill sorting

I think if you want to be a good developer, you should not only actively learn new technologies that are currently popular, such as WCF and Asp. net MVC, AJAX, etc. Skilled in using some mature technologies, such as Asp. net and WinForm. It should also have solid basic computer knowledge, such as data structures, operating systems, compilation principles, networks and data communication. Some may think that this is too difficult and theoretically difficult, but I think it takes an afternoon to study an algorithm or a data structure, isn't it a pleasure to write a story? Therefore, I plan to summarize some common data structures and algorithms, instead of spending a lot of energy on them, it is just a very relaxed mentality to complete in a relatively idle time. What I do not want the most is to turn blogging or learning technologies into a job or a burden. They should be considered a pastime in life. People always say that persistence is not easy. In fact, when you mention the word "persistence", it means that you have considered it a pain and you are not willing to do it in your heart, therefore, persistence is required. You never heard people say "I have been playing video games for ten years", "I have been watching cartoons and movies for ten years", and "Have you been spending ten years with your beloved girlfriend? I have never insisted on it because I regard it as a hobby and a pastime, just like many people playing online games.

Well, let's talk about it in a few minutes. Let's get back to the subject. There are many works in this area, so here we only provide a simple description and implementation for my own and interested friends to refer. I will try to implement it in C # And C ++. For some structures that are not easy to express in C #, I will only implement it in C ++.

This article describes the four simplest sorting methods, insert sorting, Bubble sorting, select sorting, and Hill sorting. Here I refer to it as "simple sorting ", they are easier to understand and algorithm than fast sorting, Merge Sorting, heap sorting, allocation sorting, and base sorting. For the subsequent sorting, I call it "advanced sorting ".

Simple sorting

Before you begin, declare a Convention. For the data stored in the array, it is calledRecordTo avoid confusion with names such as "element" and "object. For a record, the code used for sorting is calledKey code. Obviously, the key code selection is closely related to the record type in the array. If the record is an int value, the key code is itself. If the record is a custom object, it may contain multiple fields, so select one of these fields as the key code. Algorithms related to sorting and searching are related to the comparison of two records. The size of the two objects is determined by the client (customer object) of the algorithm program. For. NET, we can create a class that implements IComparer <T> (similar to C ++ ). For more information about IComparer <T>, refer to this Article "Sort Business Objects". Finally, in order to make the program simple, I did not handle the case where the array is empty.

1. Insert sorting algorithm IDEA

Insert sorting uses two nested loops to process the records to be sorted one by one. Each record is compared with the sequence of records that have been sorted and inserted to a proper position. Assume that the array length is n, and the outer loop control variable I is progressive from 1 to n-1, which is used to select the record to be processed. The inner loop control variable j, whose initial value is I, the value is decreased from I to 1 and compared with the previous record to determine the position to which the element is inserted. The key idea here is,When processing the I record, the previous I-1 record is already ordered.Note that because the current record is compared with the adjacent previous record, the starting value of the cyclic control variable is 1 (array subscript). If it is 0, if the previous record is-1, the array is out of bounds.

Now let's take a look at the processing of the I-th record: Suppose that the outer loop goes to the I-th record and sets its key code value to X, there may be two situations:

  1. If the previous record is larger than X, exchange 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 the previous records must be ordered and smaller than X. At this time, the record exits the layer loop. The outer loop goes forward to process the next record.
Algorithm Implementation (C #)

Public class SortAlgorithm {
// Insert sorting
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 );
}
}

// Swap the I and j elements in the array
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 preceding Console. WriteLine () method and AlgorithmHelper. PrintArray () method only print the array content in sequence for test convenience. The swap <T> () method is used to exchange two records in the array and print the number of records to be exchanged (I commented out here, but you can cancel comments to them during the test ). The outer for loop control variable I indicates that the I-th record is currently processed.

Public class AlgorithmHelper {
// Print the array content
Public static void PrintArray <T> (T [] array ){
Console. Write ("Array :");
Foreach (T item in array ){
Console. Write ("{0}", item );
}
Console. WriteLine ();
}
}

// Obtain Comparer for comparison
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 );
}
}
}

The above Code creates a ComparerFactory class to obtain an IntComparer object, which implements the IComparer <T> interface, specifies the rules for comparing the sizes of key codes of two int types. If you have a custom type, such as MyType, you only need to add a class in ComparerFactory, such as MyTypeComparer, and then enable this class to implement the IComparer <T> interface, add another method to return MyTypeComparer.

Output demo (C #)

Next, let's take a look at the client code and output:

Static void Main (string [] args ){
Int [] array = };
// 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 sorting
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

If you have never learned about algorithms and need to design an array sorting algorithm, it is very likely that you have designed a Bubble Sorting Algorithm. It is easy to implement because it is easy to understand. It also contains two layers of loops, assuming the array length is n, the outer loop control variable I increments from 0 to The N-2, this outer loop is not to process a record, but to control the number of records compared, from 0 to N-2, a total of N-1 trip. Why do n records only need to be compared to n-1 records? Let's take a look at the simplest sorting of two numbers: 4 and 3. We can get 3 and 4 by comparing them. For more records, and so on.

The exchange of Array records is completed by a layer-by-layer loop. The initial value of control variable j is n-1 (array subscript), which is reduced to 1. Array records start from the end of the array and compare with the adjacent previous record. If the previous record is larger than the key code of the current record, it is exchanged, until the subscript of the current record is 1 (the subscript of the previous record is 0 ). The whole process is like a bubble rising from the bottom, so this sorting algorithm is named Bubble sorting.

Let's examine it. According to this sorting method, after the first loop, the smallest must be at the top of the array (the subscript is 0); after the second loop, the second smallest record is located at the second position of the array (subscript is 1); and so on, after the n-1 round, the n-1 smaller record is located at the N-1 (subscript is N-2) of the array). In this case, you do not need to perform the nth round, because the last one is already at the end of the array (the subscript is n-1.

Algorithm Implementation (C #)

// Bubble Sorting
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 = };
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. Select sorting algorithm IDEA

Selecting sorting is an improvement on the Bubble sorting. From the output of the Bubble Sorting above, we can see that during the first trip, in order to switch the minimum value 13 from the first position of the Bubble Array subscript at the end of the array to 0. Similar exchanges will be made for each subsequent trip.

The sorting method is as follows: for the first query, search for the entire array, find the smallest value, and place it at the position 0 of the array. For the second query, search for n-1 records of the array, find the smallest value (the minimum value for the entire array) and place it at the 1st position of the array. Search for n-I + 1 records in the array during the I-th round and find the smallest record (for the entire array, it is smaller than I ), then place it in the position of the array I-1 (note that the array starts with 0 ). We can see that the selection of sorting significantly reduces the number of exchanges.

Note that the inner loop does not need to be decreased to the position of 1 during the I-th, as long as the loop is the same as that of I, because the previous position must be smaller than it (I .e. smaller than I ). In addition, the layer-in loop is j> I, rather than j> = I, because I is saved to lowestIndex immediately after it enters 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 minimum 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 = };
AlgorithmHelper. PrintArray (array );

SortAlgorithm. SelectionSort
(Array, ComparerFactory. GetIntComparer ());
}

Algorithm Implementation (C ++)

// Select sorting
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 sorting

Hill sorting utilizes a feature of insert sorting to optimize the sorting algorithm. This feature of insert sorting is:Insert sorting is more efficient when arrays are basically sorted.. For example, for the following array:

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

The output of insertion sorting is as follows:

We can see that although the number of shards is not reduced, the number of exchanges is obviously very small. The overall idea of hill sorting is to first let the array be basic.OrderedAnd then apply the insert sorting. The specific process is as follows: Suppose there are arrays int a [] = {, 20, 17,13, 28, 14,}, without losing the universality, we set its length to length.

In the first step, step = length/2 = 4 and divide the array into four groups. Each group has two records, and the subscript is () respectively) (); convert to a numerical value, then it is {}, {20, 14}, {17,23}, {13, 15 }. Insert and sort each group, and the group values are {28, 42}, {14,20}, {17,23}, {13, 15 }, the actual value of the original array is {28, 14, 17,13 }. Note that the position of the Group records in the original array. The subscript of the 2nd groups {} is ), therefore, the subscript of the two records in the original array is a [1] = 14; a [5] = 20.

In the second round, step = step/2 = 2. The array is divided into two groups. Each group has four records, and the subscript is (,) (,), respectively ); convert the value to a value of {28, 17,}, {, 20, 15}, and insert and sort each group to obtain }. In this case, the array is {17,13,}, which is basically ordered.

Step = step/2 = 1 in the third round. At this time, the complete insertion sorting is performed, and the final result {, 15, 17, 20, 23, 28, 42} is obtained }.

Algorithm Implementation (C #)

// Sort by hill
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 );
}
}

// Insert sorting for hill sorting
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 InsertSort () method are inserted here. startIndex is the starting index of the group and step is the step size. You can see that,The preceding insertion sorting is only a special case where step = 1 and startindex = 0..

Output demo (C #)

Static void Main (string [] args ){
Int [] array = };
AlgorithmHelper. PrintArray (array );

SortAlgorithm. ShellSort
(Array, ComparerFactory. GetIntComparer ());
}

Algorithm Implementation (C ++)

// Sort by hill
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 );
}
}
}

// Insert sorting for hill sorting
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, insertion sorting, Bubble sorting, and selection sorting are all values (n2), while Hill sorting is slightly better, which is sort (n1.5). For algorithm analysis, for more information, see related books. Here we recommend "data structure and algorithm analysis (C ++) Version 2" and "algorithm I ~ IV (C ++ implementation)-basics, data structures, sorting, and search are all very good. I mainly refer to these two books.

Thank you for reading this article. I hope this article will help you.

 

Article transferred from: http://www.tracefact.net/Algorithm/SimpleSort.aspx

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.