使用T-SQL模仿程序实现冒泡排序



/*
  Project: 此次研究的课题是模仿程序实现冒泡排序(数据库只需要排序)
*/


--1.数据库实现冒泡排序(只需要按照要求升序或倒序排列即可)
--2.数据库模仿程序实现冒泡排序
--a.申明表
--a.1 临时数据表
declare @tbl table(
  ID  int identity(1,1) primary key not null,
  Num  int not null
)




--b.插入临时数据
insert into  @tbl(Num)
select  30 as num union all
select  5  as num union all
select  20 as num union all
select  1  as num union all
select  16 as num union all
select  7  as num 
select * from  @tbl


--c.实现冒泡排序过程
declare @cnt  int ,@index int
select  @cnt  = count(0) from  @tbl
set @index = 1   
while(@index <=@cnt)    begin   --d.外层控制循环的次数(按照升序)
 
  declare @index_2 int ,@cnt_2 int,@pre_Num  int , @pre_ID int,
  @cur_Num int  , @cur_ID int
  set @index_2 =1
  select  @cnt_2 = count(0) from  @tbl
  while(@index_2 <= @cnt_2) begin   --e.控制顺序
     select  @cur_Num = Num,@cur_ID = ID from  @tbl where ID  = @index_2
     if(@index_2 = 1) begin 
         set @pre_ID =  @index_2
         set @pre_Num = @cur_Num
     end else begin
         --f.交换彼此的位置
         if(@cur_Num < @pre_Num) begin
             update  @tbl set  Num  = @pre_Num
             where ID  = @index_2              
             update  @tbl set  Num  = @cur_Num
             where ID  = @pre_ID             
             
             set @pre_ID   = @index_2    
                          
         end 
         else begin
             set   @pre_Num = @cur_Num
             set   @pre_ID  = @index_2
             set @index_2  +=1  
             continue           
         end
     end
     
     set @index_2  +=1     
  end
  set @index  +=1
end


select  * from  @tbl
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值