温州网站设计案例,商丘网站建设aliapp,子网站建设工作,深圳城乡和住房建设局网站选择排序
选择排序 #xff08;selection sort#xff09;的工作原理非常直接#xff1a;开启一个循环#xff0c;每轮从未排序区间选择最小的元素#xff0c;将其放到已排序区间的末尾。
算法原理
排序数组#xff1a;#xff08;2 4 3 1 5 2#xff09;
#xf…选择排序
选择排序 selection sort的工作原理非常直接开启一个循环每轮从未排序区间选择最小的元素将其放到已排序区间的末尾。
算法原理
排序数组2 4 3 1 5 2
2 4 3 1 5 22依次和4 3 1 5 2比较 i f ( 2 o t h e r ) ⇒ i n d e x m i n I n d e x if(2other) ⇒ indexminIndex if(2other)⇒indexminIndex比较完后交换元素位置。1 4 3 2 5 24依次和3 2 5 2比较同理得到最小元素的index比较完后交换元素位置。1 2 3 4 5 23依次和4 5 2比较同理交换元素位置。1 2 2 4 5 31 2 2 3 5 41 2 2 3 4 5
Idea
根据上述推导过程可以使用 f o r for for嵌套循环
外层用于遍历每个比较的元素内层则用于控制剩下的元素区间下划线 T ( n ) O ( n 2 ) T(n)O(n^2) T(n)O(n2)
Coding
public class bubbleSort {public static void main(String[] args) {int[] nums{1,4,6,4,5};bubbleSorted(nums);for(int i:nums){System.out.println(i);}}/*** 冒泡排序* param nums*/public static void bubbleSorted(int[] nums){int n nums.length;for(int in-1;i0;i--){for(int j0;ji;j){if(nums[j]nums[j1]){int tmpnums[j];nums[j]nums[j1];nums[j1]tmp; //大的向右边移动}}}}
}更多有趣内容访问https://github.com/TheRainbow5
参考文献
[1] https://www.hello-algo.com/chapter_sorting/selection_sort/