Four kinds of simple sorting algorithm

Four kinds of simple sorting algorithm

I think if you want to become a good developer, not only to actively learn the popular new technologies such as WCF, Asp.Net MVC, AJAX, etc., skilled application of some of the more mature technologies such as Asp.Net, WinForm. It should also have a solid basic knowledge of computer, such as data structures, operating systems, compiler theory, network and data communications. Some people may think this stuff is too abstruse and theoretical, discouraged, but I think the holidays to spend an afternoon, an algorithm research or a data structure, and then write about the experience, is it not a pleasure it ? So, I'm going to be some common data structures and algorithms to sum up, do not have to spend a lot of energy focused for some time, but in more free time in a very relaxed state of mind to complete. The last thing I want, is to write a blog or a job or learning techniques into a burden, they should be seen as a pastime life. People always say that is not easy to adhere to, in fact, when you refer to "stick" when the word of the show that you have this matter viewed as a pain, your heart and do not want to do it, it becomes necessary adhere to. You never heard people say, "I insist on playing video games for a decade," or "adhere looked ten years of animation, the film", "adhere to and get along with my girlfriend for ten years", right? I never insist, because I will it as a hobby and pastime, as many people playing online games the same.

Well, gossip So much for it, we return to the topic. Because a lot of work in this area, so just to give a simple description and realize, for myself and my friends interested reference. I will try to achieve with C # and C ++ both languages, some structures not expressed in C #, C ++ implementation only.

This article four of the most simple sorting method will be described, insertion sort, bubble sort, select, sort, Hill, I'm here referred to as "simple sorting" because they are relative to the quick sort, merge sort, heap sort, assign a rank, from the radix sort algorithm to understand and simpler. For these latter sort, I call it "advanced sorting."

Simple Sequencing

Declare before the start of a convention for the preservation of data in the array, called the unified record , in order to avoid "element", "target" and other names confused. For a record, for the sorting code, called a key . Obviously, closely related to the selection and array of key recorded in the type, if the record is int value, the key is in itself; if the record is a custom object, it is likely to contain more than one field, then select the fields of as a key. And all about sorting algorithm to find, it will compare the size relationship between the two records, and how to determine the size of two objects, the algorithm should be decided by the client program (client object). For .NET, we can create an implementation of the IComparer <T> class (for C ++ is similar). For more information about IComparer <T>, you can refer to the article " based on the sort of business objects ." Finally, to make the program simple, in the case of the array is empty and I do not deal with.

1. insertion sort

ALGORITHM

Insert sequencing using two nested loops recorded, processed one by one to be sorted. Each record has already been sorted sequence of records are compared, and insert it into place. Suppose the array of length n, the outer loop variable i to 1 by the progressive order n-1, which record for selecting the current process; inner layer loop control variable j, the initial value of i, decrementing by 1 to i, comparison with the previous recording, determines a position to which the element is inserted. The key idea here is that, when the i-th recording process, i-1 preceding record the already ordered. Note that, because the current record is compared with the adjacent previous recording, so the loop control variable starting value is 1 (array subscript), if it is 0, the previous record is -1, the array cross-border.

We now look at the case of the i-th recording process: Assume the outer loop to the i th progressive recording, set its key value X, then the time there may be two cases:

  1. If the previous record is greater than X, then swap them, until the key is smaller than the previous record X or equal.
  2. If the previous record is equal to or less than X, then all previous records must be orderly, and small than X, then exit the inner layer of the loop. The outer loop forward progression, a record processing.

Algorithm (C #)

SortAlgorithm class {public
    // insertion sort
    public static void InsertSort <T, C> (T [] Array, Comparer C)
        WHERE C: the IComparer <T>
    {          
        for (int I =. 1; I <= array.length -. 1; ++ I) {
            //Console.Write("{0}: ", I);
            int J = I;
            the while (J> =. 1 && comparer.Compare (Array [J], Array [J -. 1]) <0) {
                the swap (REF array [J], REF array [-J. 1]);
                J,;
            }
            //Console.WriteLine ();
            //AlgorithmHelper.PrintArray(array);
        }
    }

    // i-th switching array array element and the j-th element of
    private static void swap <T> ( ref T x, ref T y) {
        // Console.Write("{0}<-->{1} ", x, y);
        T temp = x;
        x = y;
        y = temp;
    }
}

Above Console.WriteLine () method and AlgorithmHelper.PrintArray () method is for convenience only test, PrintArray () method in order to print the contents of the array. swap <T> () method is used to record two arrays of the exchange, the exchange also the number of print (here I commented out, but testing can be canceled annotations thereof). For the outer loop control variable i represents the current i-th recording process.

public class AlgorithmHelper {
    // 打印数组内容
    public static void PrintArray<T>(T[] array) {
        Console.Write("   Array:");
        foreach (T item in array) {
            Console.Write(" {0}", item);
        }
        Console.WriteLine();
    }
}

// 获得Comparer,进行比较
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 code above we create a ComparerFactory class, which is used to obtain a IntComparer object that implements IComparer <T> interface provides rules to compare the size of type int between two key. If you have a custom type, such as call MyType, only you need to add a class in ComparerFactory, such as call MyTypeComparer, then let the class also implements IComparer <T> interfaces, and finally add a method to return MyTypeComparer it.

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 (C ++)

// 对int类型进行排序
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;
        }
};

// 插入排序
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 Sort

ALGORITHM

If you have not learned knowledge about aspects of the algorithm, and the need to design an array sorting algorithm, then it is quite possible to design is a bubble sort algorithm. Because it is well understood, it is also very simple to achieve. It also contains two cycles, assuming the length of the array is n, and the outer loop increments the variable i from 0 to n-2, the outer loop processing is not a record, only the number of times the comparing control, from 0 to n- 2, when comparing the n-1 times. Why n records only need to compare n-1 times? We can look at the simplest sort of two numbers: for example, 4 and 3, as long as we compare a trip, you can come to 3,4. For more records by analogy.

Switching array is completed by the recording layer in the loop, the control variable initial value of j n-1 (array subscript), has been decremented to one. Compared record array from the end adjacent the array a record, if the key is larger than a recording current record is exchanged, until the next index of the current record until the last record is 1 (in this case labeled 0). The whole process is like a bubble to rise from the bottom, so that the sorting algorithm will be named to bubble sort.

Let it be a study, in this sort, is performed after completing the first pass cycle, a certain minimum at the top most array (subscript 0); cycle after the second pass, the next smallest array of records located bis (subscript 1) position; and so, after the first cycle n-1 times, the n-1 position located at a smaller array of recording the n-1 (the subscript n-2) a. At this point no longer be the n-th cycle times, since the last end of the array has been positioned (subscript n-1) the position.

Algorithm (C #)

// 泡沫排序
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 (C ++)

// 冒泡排序
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 Sort

ALGORITHM

Selection Sort is an improvement of the bubble sort, bubble sort output from the above can be seen in the first trip, in order to lower the minimum value of the array by the end of the array 13 is marked as the first bubbling position 0 , we conducted a number of exchange. For each subsequent trip, will be similarly exchanged.

Selection Sort idea is: For the first pass, the search through the array to find the smallest, and then placed in a location in the array number 0; for the second pass, n-1 recording search array to find the smallest (for the whole it is a small array of times), and then placed into the No. 1 array position. When the i-th times, the search array of n-i + 1 records, to find the smallest record (for the entire array, it is the i-th small), then placed in the position i-1 of the array (note that the array from 0 to beginning). As can be seen, selection sort significantly reduces the number of exchanges.

Needs attention is: when i first trip, the inner loop does not need decrements to position 1, as long as circulation to the same i can, because before certain position than it is small (that is, the i small) . Further cycles inner layer is j> i, instead of j> = i, i since after entering the loop was immediately stored in a lowestIndex.

Algorithm (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;        // 最小记录的数组索引
        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 (C ++)

// 选择排序
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. Shell sort

Hill took advantage of a sort insertion sort features to optimize the sorting algorithm, insertion sort of this feature is: when an array of basic and orderly time, insertion sort more efficient . For example, an array follows:

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

Insertion sort output are as follows:

It can be seen, although the comparison is not to reduce the number of times, but the number of exchanges is obviously very small. The overall idea is to let Hill sorting an array of basic and orderly , and finally apply insertion sort. Specific process is as follows: Suppose an array int a [] = {42,20,17,13,28,14,23,15} , without loss of generality, we set the length for length.

When the first trip, step step = length / 2 = 4, the array will be divided into four groups of two records, the subscript, respectively (0,4) (1,5) (2,6) (3 , 7); converted to a number, for the {42,28}, {20, 14}, {17, 23}, {13, 15}. Then insertion sort each packet, then the packet is the value {28,42}, {14, 20}, {17, 23} {13, 15}, and the value of the actual original array becomes {28 , 14,17,13,42,20,23,15}. It is noted here that the position of the packet is recorded in the original array, the second packet to {14, 20}, its index is (1,5), these two records in the original array subscript respectively a [1] = 14; a [5] = 20.

When the second pass, step step = step / 2 = 2, the array will be divided into two groups, each group of four records, the subscript respectively (0,2,4,6) (1,3,5,7 ); converted to a number, for the {28,17,42,23}, {14,13,20,15}, then each packet insertion sort, to give {17,23,28,42} {13, 14, 15}. In this case it would be an array of {17,13,23,14,28,15,42,20}, it has been basically in order.

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

Algorithm (C #)

// 希尔排序
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);
    }
}

// 用于希尔排序的插入排序
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 insertion sort InsertSort () method parameters, a starting index startIndex packet, step is the step size, it can be seen, in front of the insertion sort only where step = 1, startindex = 0 is a special case .

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 (C ++)

// 希尔排序
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);
        }
    }
}

// 用于希尔排序的插入排序
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 price above three algorithms, insertion sort, bubble sort, selection sort, are [Theta] (the n- 2 ), and Hill sorting slightly better, is [Theta] (the n- 1.5 ), on algorithmic analysis, we are interested can refer to books. It is recommended " Data Structures and Algorithm Analysis (C ++ Edition) Second Edition " and " algorithm I ~ IV (C ++ to achieve) - based on data structures, sorting and searching ," very good, I also refer to the main two books .

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

Reproduced in: https: //www.cnblogs.com/JimmyZhang/archive/2008/10/02/1303137.html

Guess you like

Origin blog.csdn.net/weixin_33834679/article/details/93444051