1.Bubble Sort
Bubble Sort (Bubble Sort) is the simplest kind of sorting. It goes through all the elements of the array repeatedly. Elements are compared two by two in a ring, until the number is ended when there are no more numbers to exchange, and then the next number is added until the entire array is sorted. Because they float one by one, it is called bubble sort. Double cycle time O(n^2)
Algorithm description:
Compare two adjacent data if. The first one is greater than the second one, just swap the two numbers
Do the same 1 work for each adjacent number, so that from the beginning to the end, one team is at the end The number is the largest number.
Operations on all elements except the last one.
Repeat steps 1~3 until the order is completed.
Code visualization:
##Code implementation:
2. Selection Sort
Select Sort is an intuitive sorting, by determining the maximum or minimum value of a Key, and then sorting from the band Find the largest or smallest number and swap it to the corresponding position. Choose the next best option. The double loop time complexity is O(n^2)
Algorithm description:
- In an unordered sequence of length N In the array, traverse n-1 numbers for the first time to find the smallest one and exchange it with the first number.
- Traverse n-2 numbers starting from the next number for the second time, find the smallest number and exchange it with the second number.
- Repeat the above operation until the smallest number and the n-1th number are exchanged for the n-1th traversal, and the sorting is completed.
Algorithm visualization:
## Code implementation:
<code><p><img src="https://img.php.cn/upload/article/000/000/164/168309619043778.png" alt="How to implement bubble sort, selection sort, quick sort in Java"><br></p></code>
3. Quick Sort
Quick Sort (QuickSort) is the most commonly used sort after excluding stability factors. I would like to introduce two ways to use it. One is to implement the qsort function directly in the header file of my stdlib.h file, which is the same as writing normal code. Array sorting is implemented by using qsort (array name, length, sizeof (first number length), compInc/comoDec). The latter is in the form of recursive calls.
Algorithm description:
Select an element from the sequence as the benchmark. Rearrange the sequence, put all the ones smaller than the benchmark in front of the benchmark, and put them in the back (the same size can be on either side). After completion, the benchmark will be in the middle of the partition. Sort the subsequences that are smaller than the base element and the heavy rain base element through recursive calls.
Algorithm visualization:
## Code implementation:
The above is the detailed content of How to implement bubble sort, selection sort, quick sort in Java. For more information, please follow other related articles on the PHP Chinese website!