Home >Java >javaTutorial >Write a function to sort the data in the array from small to large
Bubble Sort is a relatively simple sorting algorithm in the field of computer science.
It repeatedly visits the column of elements to be sorted, compares two adjacent elements in turn, and swaps them if their order (such as from large to small, first letter from A to Z) is wrong. . The work of visiting elements is repeated until no adjacent elements need to be exchanged, which means that the element column has been sorted.
If you want to know more about java, you can click: java tutorial
The name of this algorithm The reason is that larger elements will slowly "float" to the top of the sequence through exchange (arranged in ascending or descending order), just like the carbon dioxide bubbles in carbonated drinks will eventually float to the top, hence the name "bubble sorting".
The principle of the bubble sort algorithm is as follows:
1. Compare adjacent elements. If the first one is bigger than the second one, swap them both.
2. Do the same work for each pair of adjacent elements, from the first pair at the beginning to the last pair at the end. At this point, the last element should be the largest number.
3. Repeat the above steps for all elements except the last one.
4. Continue to repeat the above steps for fewer and fewer elements each time until there are no pairs of numbers to compare.
public class Sort { public static void main(String[] args){ int[] arr = {6,3,2,1,7}; for(int i = 0;i<arr.length-1;i++){//外层循环n-1 for(int j = 0;j<arr.length-i-1;j++){//内层循环n-i-1 if(arr[j]>arr[j+1]){//从第一个开始,往后两两比较大小,如果前面的比后面的大,交换位置 int tmp = arr[j]; arr[j] = arr[j+1]; arr[j+1] = tmp; } } } System.out.println(Arrays.toString(arr)); } }
The above is the detailed content of Write a function to sort the data in the array from small to large. For more information, please follow other related articles on the PHP Chinese website!