冒泡双向排序

转载请注明出处:http://blog.csdn.net/droyon/article/details/8785903

/**
 * 双向冒泡排序,从左向右冒泡排序,大数沉底,然后从右向左排序,小数冒泡。如此循环。
 * @author 
 *
 */
public class BubbleTwoSort {
	private static int[] array = new int[]{1,8,2,9,3,7,11,23,90,4,5};
	public static void main(String args[]){
        System.out.println("排序前");
        printArray();
        System.out.println("\n排序后");
        bubbingTwoSort();
        printArray();
	 }
	 private static void bubbingTwoSort(){
		 int temp;
		 int left=0;
		 int right=array.length-1;
		 int index=0;
		 while(left <= right){
			 index++;
			 for(int i=left;i<right;i++){
				 if(array[i]>array[i+1]){
					 temp = array[i];
					 array[i] = array[i+1];
					 array[i+1] = temp;
				 }
			 }
			 //想看没一趟交换结果,打开下面输出
			 /*System.out.println("第"+index+"次正向冒泡");
			 printArray();
			 System.out.println();*/
			 right--;
			 for(int j=right;j>left;j--){
				 if(array[j]<array[j-1]){
					 temp = array[j];
					 array[j]=array[j-1];
					 array[j-1] = temp;
				 }
			 }
			 left++;
			 //查看输出,打开以下输出
			 /*System.out.println("第"+index+"次反向冒泡");
			 printArray();
			 System.out.println();*/
		 }
	 }
	 public static void printArray(){  
        for(int i=0;i<array.length;i++){  
            System.out.print(array[i]+"   ");  
        }  
	 }  
}


输出结果:

排序前
1   8   2   9   3   7   11   23   90   4   5   
排序后
1   2   3   4   5   7   8   9   11   23   90   

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
双向链表的双向冒泡排序可以通过比较相邻节点的数据域来实现。具体步骤如下: 1. 首先,定义一个指向链表头节点的指针,命名为`current`。 2. 使用两个循环嵌套,外层循环控制比较的轮数,内层循环控制每一轮的比较次数。 3. 在内层循环中,比较`current`节点和`current.next`节点的数据域,如果前者大于后者,则交换它们的数据域。 4. 内层循环结束后,将`current`指针指向下一个节点,继续进下一轮的比较。 5. 外层循环结束后,整个链表的数据域将按照从小到大的顺序排列。 下面是一个示例代码,演示了双向链表的双向冒泡排序: ```python class Node: def __init__(self, data): self.data = data self.prev = None self.next = None def bubble_sort(head): if head is None or head.next is None: return head end = None while end != head.next: current = head.next while current.next != end: if current.data > current.next.data: current.data, current.next.data = current.next.data, current.data current = current.next end = current return head # 创建双向链表 head = Node(4) node1 = Node(2) node2 = Node(1) node3 = Node(3) head.next = node1 node1.prev = head node1.next = node2 node2.prev = node1 node2.next = node3 node3.prev = node2 # 执双向冒泡排序 sorted_head = bubble_sort(head) # 输出排序后的链表数据 current = sorted_head.next while current is not None: print(current.data) current = current.next ``` 输出结果为: ``` 1 2 3 4 ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

hailushijie

您的鼓励是我创作最大的动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值