5 没事儿就学习:快速排序(Fortran)( 二 )


5  没事儿就学习:快速排序(Fortran)

文章插图
program addNumbers! This common program can simulate quick sortimplicit none! Type declarationsreal :: numberList(5) = (/5, 3, 7, 0, 1/)integer :: i, startLoc, endLocinterfacerecursive integer function QuickSort(list, startLoc, endLoc)real list(5)integer startLoc, endLocend function QuickSortend interface! Executable statementsstartLoc = 1endLoc = 5i = QuickSort(numberList, startLoc, endLoc)do i = 1, 5print *, numberList(i)end doend program addNumbersrecursive integer function QuickSort(list, startLoc, endLoc)real :: list(5)integer :: startLoc, endLocinteger :: low, highreal :: oriValuelow = startLochigh = endLocoriValue = http://www.kingceram.com/post/list(startLoc)if (low .ge. high) thenreturnend ifdo while(low < high)do while(low < high .and. list(high)> oriValue)high = high - 1end dolist(low) = list(high)do while(low < high .and. list(low) < oriValue)low = low + 1end dolist(high) = list(low)end dolist(low) = oriValueoriValue = http://www.kingceram.com/post/QuickSort(list, startLoc, low - 1)oriValue = QuickSort(list, low + 1, endLoc)QuickSort = lowend function QuickSort
5  没事儿就学习:快速排序(Fortran)

文章插图
再加一个无聊的冒泡排序
【5没事儿就学习:快速排序(Fortran)】program testimplicit nonereal :: list(10) = (/4, 2, 7, 3, 9, 6, 7, 1, 0, 8/)integer :: length = 10, res, iinterfaceinteger function BubbleSort(list, length)real list(10)integer lengthend function BubbleSortend interfaceres = BubbleSort(list, 10)do i = 1, 10print *, list(i)end doend program testinteger function BubbleSort(list, length)real :: list(10)integer :: innerLoof, outerLoofreal :: middledo outerLoof = 1, lengthdo innerLoof = outerLoof + 1, lengthif (list(outerLoof) > list(innerLoof)) thenmiddle = list(outerLoof)list(outerLoof) = list(innerLoof)list(innerLoof) = middleend ifend doend doBubbleSort = 1end function BubbleSort