## CSDN博客

### T-SQL单向冒泡排序算法

--2004-09-16
--Groundsel
--单向冒泡排序算法：从上到下
Create Procedure sp_Bubble_Sort
@ID Varchar(8000) --以逗号分隔
As
Create Table #Order
(ID Int Identity(1,1),Value Int)

Declare @I   Smallint,
@Len   SmallInt,
@CharIndex  SmallInt,
@Value1  SmallInt,
@Value2  SmallInt,
@Flag   Bit

Select @I = 0
Select @Len = Len(@ID)

--将字符串转为临时表
While @I < @Len
Begin
Select @CharIndex = CharIndex(',',@ID)
If @CharIndex <> 0
Begin
Insert Into #Order(Value)
Select Left(@ID,@CharIndex - 1)
Select @ID = Right(@ID,Len(@ID) - @CharIndex)
Select @I = @I + @CharIndex
End
Else
Begin
Insert Into #Order(Value)
Select @ID
Select @I = @Len
End
End

--@Flag标志排序是否完成
Set @Flag = 1

--循环的次数即为排序的趟数
While IsNull(@Flag,0) = 1
Begin
Set @I = 1
Set @Flag = 0
Set @Value1 = Null
Set @Value2 = Null

Declare MyCur Cursor For Select Value From #Order
Open MyCur
Fetch Next From MyCur Into @Value1

While @@Fetch_Status = 0
Begin
Select @Value2 = Value From #Order Where ID = @I + 1
If @Value1 > @Value2
Begin
Set @Flag = 1
Update #Order Set Value = @Value2 Where ID = @I
Update #Order Set Value = @Value1 Where ID = @I + 1
End
Select @I = @I + 1
Select @Value2 = Null

Fetch Next From MyCur Into @Value1
End
Close MyCur
Deallocate MyCur
End

Set @I = 0
Set @ID = ''

Select @ID = @ID + Cast(Value As Varchar(20)) + ','
From #Order

Select Left(@ID,Len(@ID) - 1)

Go
Execute sp_Bubble_Sort '23,6,2,12,19,-6'

----------------
-6,2,6,12,19,23

0 0