算法原理:
将临近的数字两两比较,按照从小到大或者从大到小的顺序交换,这样一趟之后,最大或者最小的数字被放到最后一位;然后再从头开始两两比较交换,至倒数第二位结束;如此直至所有数字排序完毕
java实现:
用数组:
public class BubbleSort {
/**
* 线性表实现冒泡排序,从小到大排序
* @param arrays
* @return
*/
public int[] bubbleSort(int[] arrays){
int len = arrays.length;
while(len > 0){
for(int i = 0; i < len - 1; i++){
if(arrays[i] > arrays[i+1]){
swap(arrays,i,i+1);
}
}
len--;
}
return arrays;
}
private void swap(int[] arrays, int i, int j) {
int tmp = arrays[i];
arrays[i] = arrays[j];
arrays[j] = tmp;
}
public static void main(String[] args){
int[] arrays = {10,5,4,8,74,58,12,14,14,56,3,1,11,57,41,102};
arrays = new BubbleSort().bubbleSort(arrays);
for(int i = 0; i < arrays.length; i++){
System.out.print(arrays[i]);
System.out.print(",");
}
}
}
/**
* 单链表实现冒泡排序,从小到大排序
*
*/
public class BubbleSortWithLink {
public Node bubbleSort(Node head){
Node result = head;
Node preNode = null;
Node curNode = head;
Node nextNode = head.getNextNode();
Node endNode = null;
while(result != endNode){
preNode = null;
curNode = result;
while(curNode.getNextNode() != endNode){
nextNode = curNode.getNextNode();
if(curNode.getValue() > nextNode.getValue()){
result = exchange(result,preNode,curNode,nextNode);
preNode = nextNode;
curNode = nextNode.getNextNode();
} else{
preNode = curNode;
curNode = nextNode;
}
}
endNode = curNode;
}
return result;
}
private Node exchange(Node head,Node preNode, Node curNode, Node nextNode) {
Node tmp = null;
tmp = nextNode.getNextNode();
if( null == preNode){
curNode.setNextNode(tmp);
nextNode.setNextNode(curNode);
return nextNode;
} else {
preNode.setNextNode(nextNode);
nextNode.setNextNode(curNode);
curNode.setNextNode(tmp);
return head;
}
}
public static void main(String[] args){
Node node1 = new Node(10);
Node node2 = new Node(5,node1);
Node node3 = new Node(8,node2);
Node node4 = new Node(19,node3);
Node node5 = new Node(28,node4);
Node node6 = new Node(12,node5);
Node node = new BubbleSortWithLink().bubbleSort(node6);
while(node.getNextNode() != null){
System.out.print(node.getValue());
System.out.print(",");
node = node.getNextNode();
}
System.out.print(node.getValue());
}
}
public class Node {
Node(int value) {
this.value = value;
}
Node(int value, Node node) {
this.value = value;
this.nextNode = node;
}
private int value;
private Node nextNode;
public int getValue() {
return value;
}
public void setValue(int value) {
this.value = value;
}
public Node getNextNode() {
return nextNode;
}
public void setNextNode(Node nextNode) {
this.nextNode = nextNode;
}
}