作者Yagyu (烟火)
看板Fortran
标题[问题] 气泡排序
时间Tue Mar 8 20:09:29 2011
最近自己参考彭国伦的书写了气泡排序法,程式如下面列的。
主要流程是先决定要排几个整数,然後用乱数产生这些数,最後再由小排到大排序。
程式跑起来虽然没问题,但是我想到一个问题是如果乱数产生一组相同的数,
这样子程式会不会发生问题,如果会,该怎麽处理比较好?
希望有这方面经验的前辈给我一点建议,谢谢各位!
program Bubble_Sort_Test
implicit none
integer, allocatable :: Ran(:)
integer :: i, j, temp, RanSz
integer, parameter :: k=1000
real :: t, start, finish
write(*,*) "Input the size of the allocatable matrix: "
read(*,*) RanSz
call cpu_time(start)
allocate(Ran(RanSz))
call random_seed()
open(unit=3,file='bst.txt')
write(3,*) "----- Not Sorted -----"
do i=1,RanSz,1
call random_number(t)
Ran(i)=int(k*t)
write(3,*) Ran(i)
end do
write(3,*) "----- Not Sorted -----"
do i=RanSz-1,1,-1
do j=1,i,1
if (Ran(j)>Ran(j+1)) then
temp=Ran(j)
Ran(j)=Ran(j+1)
Ran(j+1)=temp
end if
end do
end do
write(3,*) "----- Sorted -----"
do i=1,RanSz,1
Write(3,*) Ran(i)
end do
write(3,*) "----- Sorted -----"
call cpu_time(finish)
write(3,3000) finish-start
3000 format("***** Time = ", f7.3, "seconds. *****")
stop
end program Bubble_Sort_Test
--
※ 发信站: 批踢踢实业坊(ptt.cc)
◆ From: 219.84.56.207
1F:→ charlesdc:内容没看......但是如果气泡写对不会遇到你说的问题 03/09 21:56
2F:→ Cypresslin:试试看就知道会不会出问题了 03/10 12:16
感谢回应,自己是测试过了,的确没这问题。
不过气泡排序真的蛮慢的,跟快速排序相比真的差很多。
※ 编辑: Yagyu 来自: 219.84.56.207 (03/10 14:04)