Write in front
I've been busy with my work in the past two months and haven't taken time to take care of my blog. It's rare to take a day off today. I want to review a little bit from the most basic algorithm, and constantly improve my study while reviewing. I want to implement my own small algorithm library by the end of May next year.
Why do you want to write an algorithm library
In the three months since I graduated and started working now, to be honest, basic algorithms are not widely used, but algorithmic thinking has always accompanied and affected my work. In the past, learning algorithms were scattered on-demand learning with teacher liuyubo. I have never systematically sorted them out, let alone implemented the algorithm library. On the one hand, it actually wants to make up for the regret during the University. On the other hand, it also wants to leave something for the younger brothers and sisters who have not graduated, which is worth learning.
About the language used
For the time being, I will consider implementing it in two languages, Java and C #. Java is preferred because the language is simpler and has a wide audience among students. As mentioned earlier, more consideration should be given to making learning templates for younger and younger students. Another language is C #. First, C # is a brother language with Java, and the syntax structure and characteristics of the two languages are very similar. Second, because I am engaged in game client research and development, C # is the most frequently used language in my current work.
About extension
I built a new warehouse in GitHub, named Zhu Yu, from the south of Shanhaijing. "If there is grass, it looks like leek and green, and its name is Zhu Yu. Eating without hunger." I think the algorithm is beautiful, and eating without hunger is the best interpretation of it.
In each article, I will implement the algorithm in the order of Java and c#. After implementation, I will organize them into ZhuYu. Later, I will use my spare time to implement them in C + + language and Python language and store them in ZhuYu as extensions. I hope interested leaders can maintain and improve with me.
Let's go straight to the topic:
Select sort
In short, selective sorting refers to selecting the smallest element from the unprocessed array every time, and reloading the selected number into an array in turn. This refers to ascending order. If descending order is required, select the largest element from the unprocessed array each time.
For example, chestnuts:
Suppose I have an array {1,6,4,2,8,9}. If you use selective sorting, let's look at it step by step:
- First select the smallest element from the array, 1. So the remaining elements are 6, 4, 2, 8, 9
- Select the smallest element from the remaining elements, this time 2. At this time, the remaining elements are 6, 4, 8 and 9
- Next, repeat the above operation and take out 4, 6, 8 and 9 in turn
- Take out the order of elements 1, 2, 4, 6, 8, 9. This is the order after sorting.
If you need to get a group of descending data, you can choose a maximum number at a time. From the above reasoning, we can quickly get the most important steps of the algorithm.
1.Traversal of arrays 2.Find the smallest decimal in the array 3.Store the minimum number
Move elements without opening up new space
In order to get the sequential array, you can put the elements taken out each time into a new array. Pay attention! Since a new array will open up space, the above ideas can be optimized. You can move elements in the original array to make the array active.
In the above example, int[] arr{1, 6, 4, 2, 8, 9} performs the following deduction. Because I didn't prepare ppt tonight, I hope I can take a pen and paper and draw a drawing process with me in my book,
- First, introduce an index to point to the first element in the array. That is, arr[0].
- Next, find the smallest element in the array. Compare the size of all the remaining elements with the element arr[0], that is, judge 6 > arr[0], 4 > arr[0], 2 > arr[0], 8 > arr[0], 9 > arr[0] in turn (leave a pit here)
- The last step found that 1 is the smallest. Just point the index to the next number arr[1], temporarily 6 in the array. At this time, the order of the array is still 1, 6, 4, 2, 8 and 9.
- next!! Compare all the remaining elements with 6 in order, that is, cycle all the elements after 6. Judge successively, 4 < arr [1], 2 < arr [1], 8 < arr [1], 9 < arr [1]; First, 4 < arr [1]. If 4 < 6 is found, then 4 and 6 are exchanged. At this time, the array becomes 1, 4, 6, 2, 8 and 9.
- ⚠️, After the position is exchanged, arr[1] will correspondingly become 4, and the next comparison 2 < arr[1] will become a comparison of 2 < 4. Similarly, if the position is exchanged, the next comparison will be 8 < arr[1], that is, 8 < 2, and 8 is not less than 2, then continue the next cycle.
- Next, the comparison of 9 < arr [1], that is, 9 < 2, is not tenable. At this point, all elements have been compared. The array becomes 1, 2, 6, 4, 8, 9. Looking at the red array in step 3, it seems that the second smallest number is placed in the second position, but in fact it exchanges 6 and 4 first, followed by 4 and 2.
- 1 and 2 are sorted positions. Remember that the index points to arr[1]. In 1, 2, 6, 4, 8 and 9, move the pointer to the next position, namely arr[3]. What should I do next? That is, compare the remaining elements with 6 respectively. If they are small, exchange positions. Note that arr[3] may change.
- ... constantly judge and move the index until the index points to the last number.
Through the steps, we can quickly get the selection sorting algorithm:
public void sort(int[] arr) { for (int i = 0; i < arr.length; i++) { int minIndex = i; // Mark the index of the minimum value first, and exchange after marking for (int j = i; j < arr.length; j++) { if (arr[j]< arr[minIndex])) minIndex = j; } swap(arr, i, minIndex); } } private void swap(int[] arr, int i, int j) { int tmp = arr[i]; arr[i] = arr[j]; arr[j] = tmp; }
Add generic constraints to the algorithm
The code is rewritten into a tool class, which can be called externally directly using Selection.Sort().
1.Java implementation
/** * Select sort * * @description: Each selection has not processed the smallest element in the element * @author: WenRuo * @date: 2021/10/20 20:01 */ public class SelectionSort { private SelectionSort() {} /** * Ascending order * @param arr */ public static <E extends Comparable<E>> void sortASC(E[] arr) { for (int i = 0; i < arr.length; i++) { int minIndex = i; for (int j = i; j < arr.length; j++) { if (arr[j].compareTo(arr[minIndex]) < 0) minIndex = j; } swap(arr, i, minIndex); } } /** * Descending order * @param arr */ public static <E extends Comparable<E>> void sortDESC(E[] arr) { for (int i = 0; i < arr.length; i++) { int minIndex = i; for (int j = i; j < arr.length; j++) { if (arr[j].compareTo(arr[minIndex]) > 0) minIndex = j; } swap(arr, i, minIndex); } } private static <E> void swap(E[] arr, int i, int j) { E tmp = arr[i]; arr[i] = arr[j]; arr[j] = tmp; } }
2.C# implementation
public class SelectionSort { private SelectionSort(){} /// <summary> ///Ascending order /// </summary> /// <param name="arr"></param> public static void SortAsc(int[] arr) { for (int i = 0; i < arr.Length; i++) { int minIndex = i; for (int j = i; j < arr.Length; j++) { if (arr[j] < arr[minIndex]) minIndex = j; } Swap(arr, i, minIndex); } } /// <summary> ///Descending order /// </summary> /// <param name="arr"></param> public static void SortDesc(int[] arr) { for (int i = 0; i < arr.Length; i++) { int minIndex = i; for (int j = i; j < arr.Length; j++) { if (arr[j] > arr[minIndex]) minIndex = j; } Swap(arr, i, minIndex); } } private static void Swap(int[] arr, int i, int j) { int tmp = arr[i]; arr[i] = arr[j]; arr[j] = tmp; } }