Selectionsort is a simple and intuitive sorting algorithm. Its working principle is as follows: first, find the minimum element in the unordered sequence, store it to the starting position of the sorting sequence, and then continue to find the minimum element from the remaining unordered elements, and put it at the end of the sorting sequence. And so on until all elements are sorted.
Selection sort is a simple and intuitive sorting algorithm. It works as follows:
First, find the minimum element in the unordered sequence and store it to the starting position of the sorting sequence. Then, find the minimum element from the remaining unordered elements and put it at the end of the sorting sequence. And so on until all elements are sorted.
The following is an animated demonstration:
The idea of selecting sorting is very direct, isn't it necessary to sort it? Well, I will find the smallest in all sequences and place them in the first position. Then let's look at the smallest of the remaining elements and place them in the second position ...... And so on, you can complete the sorting. We can clearly find that the sorting is a fixed position to find elements. Compared with the placement of fixed elements in the Insertion sorting, this is a two-way of thinking. However, there are two major routes to Rome, with the same purpose.
Below is the C language implementation:
# Include
# Include
Void main () {int I; int arr [10]; int count; printf ("The array before sorting is:"); srand (int) time (0 )); for (I = 0; I <10; I ++) {arr [I] = rand () % 100; printf ("% d", arr [I]);} count = sizeof (arr)/sizeof (arr [0]); selectionSort (arr, count); printf ("\ n sorted array :"); for (I = 0; I <10; I ++) {printf ("% d", arr [I]) ;}} void selectionSort (int data [], int count) {int I, j, min, temp; for (I = 0; I <count; I ++) {/* find the minimum */min = I; for (j = I + 1; j <count; j ++) if (data [j] <data [min]) min = j; temp = data [I]; data [I] = data [min]; data [min] = temp ;}}
From the thought of selecting sorting or the code above, we can hardly see that finding the smallest element requires a loop process, while sorting requires a loop process. Therefore, it is obvious that the time complexity of this algorithm is O (n * n. This means that when the value of n is small, the algorithm can ensure a certain speed. when n is large enough, the efficiency of the algorithm will be reduced. As n increases, the algorithm time increases rapidly. Therefore, pay special attention to this feature.
Additional reading
The topic list of this article is as follows:
- Introduction to Algorithms: Principles and implementation of selective sorting
This article is available at http://www.nowamagic.net/librarys/veda/detail/1849.