When we learn programming languages, we are exposed to many sort algorithms, and here we summarize the common sorting algorithms. Not regularly updated.
* Actually there are methods like Collections.sort () in Java that automatically sort us out, but the learning sort algorithm allows us to better understand a programming language.
1. Bubble Sort:
This algorithm is one of the most basic and famous algorithms.
1 Public Static voidBubblesort (int[] arr) {2 for(inti = 0; i < arr.length-1; i++) {3 for(j = 0; J < arr.length-1-I; j + +) {4 if(Arr[j] > arr[j + 1]) {5 intt =Arr[j];6ARR[J] = arr[j + 1];7Arr[j + 1] =T;8 }9 }Ten } One}
Note: The idea of the algorithm is that the previous element of the array is compared with the following element, if the previous element is larger, the value of the two elements is exchanged, so that the first round of the most important element is located in the last position of the array, that is, arr[arr.length-1]; The second round is that all elements except the last element are compared again to find the second largest number. And so on.
2. Select Sort:
The algorithm's popularity is quite similar to bubble sort.
1 Public Static voidSelectsort (int[] arr) {2 for(inti = 0; i < arr.length-1; i++) {3 for(intj = i + 1; J < Arr.length; J + +) {4 if(Arr[i] >Arr[j]) {5 intt =Arr[i];6Arr[i] =Arr[j];7ARR[J] =T;8 }9 }Ten } One}
Note: The idea of the algorithm is that the first element of the array is compared with all subsequent elements, if the element is larger, the value of two elements is exchanged, so that the first round of the most important element is located in the last position of the array, that is, arr[arr.length-1]; Then the second element is compared to all subsequent elements. And so on.
Java implementation of common sorting algorithms-1