冒泡排序

算法原理:

將臨近的數字兩兩比較,按照從小到大或者從大到小的順序交換,這樣一趟之後,最大或者最小的數字被放到最後一位;然後再從頭開始兩兩比較交換,至倒數第二位結束;如此直至所有數字排序完畢

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;
}
}

發佈了31 篇原創文章 · 獲贊 0 · 訪問量 2萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章