!= 关于 ++ 再看 pri int ava 不为 分享
其实冒泡排序应该用例子证明,设数组长度为N。
1.比较相邻的前后二个数据,如果前面数据大于后面的数据,就将二个数据交换。
2.这样对数组的第0个数据到N-1个数据进行一次遍历后,最大的一个数据就“沉”到数组第N-1个位置。
3.N=N-1,如果N不为0就重复前面二步,否则排序完成。
看了基本的方法,就写个代码验证下
- // 2.冒泡排序
- @Test
- public void test2() {
- int[] arr={14,9,8,15,34,5};
- int temp=0;
- for(int i=0;i<arr.length;i++){
- for(int j=0;j<arr.length-1;j++){
- if(arr[j]>arr[j+1]){
- temp=arr[j];
- arr[j]=arr[j+1];
- arr[j+1]=temp;
- }
- }
- }
- //遍历输出有三种输出方式,可以参考我博客的3中遍历输出的方式
- for(int a:arr){
- System.out.println(a);
- }
- }
思想:先在所有序列中先找到最小的,然后放到第一个位置。之后再看剩余元素中最小的,放到第二个位置……以此类推,就可以完成整个的排序工作了。
- @Test
- public void test4() {
- int[] arr = { 14, 9, 8, 90, 34, 5,78 };
- int minIndex;
- int temp;
- for (int i = 0; i < arr.length-1; i++) {
- minIndex=i;
- for (int j = i + 1; j < arr.length; j++) {
- if (arr[j] < arr[minIndex]) {
- minIndex =j;
- }
- }
- if(minIndex!=i){
- temp=arr[i];
- arr[i]=arr[minIndex];
- arr[minIndex]=temp;
- }
- }
- for (int i : arr) {
- System.out.println(i);
- }
- }
冒泡排序与选择排序(经典版)----java基础总结
!= 关于 ++ 再看 pri int ava 不为 分享
原文:http://www.cnblogs.com/chenyanlong/p/7818964.html
来源: http://www.bubuko.com/infodetail-2390645.html