双向冒泡排序

编写一个双向冒泡排序算法,即在排序过程中以交替的正,反两个方向进行遍历,若第一趟吧关键字最大的记录放到最末尾,则在第二趟吧关键字最小的记录放到最前面。如此反复进行。

 

void dbubble(int a[],int i,int j,int flag)
{
 int y,temp;
 if(i==j)
  return;
 if(flag==1)
 {
  for(y=i;y<=j-1;y++)
  {
   if(a[y]>a[y+1])
   {
    temp=a[y];
    a[y]=a[y+1];
    a[y+1]=temp;
   }
  }
  flag=0;
  j--;
  dbubble(a,i,j,flag);
 }
 else if(flag==0)
 {
  for(y=j;y>i;y--)
  {
   if(a[y]<a[y-1])
   {
    temp=a[y];
    a[y]=a[y-1];
    a[y-1]=temp;
   }
  }
  flag=1;
  i++;
  dbubble(a,i,j,flag);
 }
}
  • 0
    点赞
  • 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
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值