java 冒泡排序
}
}
arr[j]?=?temp;
arr[i]?=?arr[j];
int?temp?=?arr[i];
//?java?是引用传递
private?void?swap(int?i,?int?j)?{
//?左右值交换
}
}
}
}
swap(j,?j?-?1);
if?(arr[j]
//?后面的/下面的水泡?小于?上面的水泡,就移位
for?(int?j?=?elements?-?1;?j?>?i;?j--)?{
//?每一轮比较,找出本轮的最小值
for?(int?i?=?0;?i
//?4?3?2?1,按冒泡排序的话,需要进行3轮比较可以了
public?void?bubbleSort()?{
}
System.out.println();
}
System.out.print(arr[i]?+?"?");
for?(int?i?=?0;?i
public?void?show()?{
}
arr[elements++]?=?value;
public?void?insert(int?value)?{
}
this.elements?=?0;
//?初始化状态,数组里的默认元素个数为0
arr?=?new?int[maxSize];
this.maxSize?=?maxSize;
public?MyArrayWithBubbleSort(int?maxSize)?{
private?int?elements;
//?当前数组里,有多少个元素;有点类似于指针,索引的意思
private?int?maxSize;
//?数组,最多能存储多少个元素
private?int[]?arr;
//?声明一个数组
public?class?MyArrayWithBubbleSort?{
*/
*?@author?erjun?2017年12月11日?上午9:20:28
*
*?实际生活中:小学时,需要根据身高进行座位排序,就可以使用冒泡排序进行。
*
*?冒泡排序核心:1、从数组的最后一个元素,开始比较;2、两两比较,满足条件的话,就需要进行位置的互换
*
*?特点是:带有冒泡排序功能
*
*?自定义数组类
/**
package?com.xingej.algorithm.sort.bubble;
单元测试:
- package?com.xingej.algorithm.sort.bubble;
- import?org.junit.Test;
- public?class?MyArrayWithBubbleSortTest?{
- ????@Test
- ????public?void?test()?{
- ????????MyArrayWithBubbleSort?bubbleSort?=?new?MyArrayWithBubbleSort(6);
- ????????bubbleSort.insert(2);
- ????????bubbleSort.insert(3);
- ????????bubbleSort.insert(1);
- ????????bubbleSort.insert(7);
- ????????System.out.println("------排序前----打印输出------");
- ????????bubbleSort.show();
- ????????bubbleSort.bubbleSort();
- ????????System.out.println("------排序后----打印输出------");
- ????????bubbleSort.show();
- ????}
- }
代码已托管到
https://github.com/xej520/xingej-algorithm
Java排序算法之冒泡排序
java 冒泡排序
原文:http://blog.51cto.com/xingej/2049607
来源: http://www.bubuko.com/infodetail-2425456.html