閑著沒事,就聽聽網易課堂上的老外講演算法導論,下面就實現了一下快速排序,用了兩種方式去實現的,一種是老外講的那種,
在找partitin pivot的時候從左+1到右的遍曆,遍曆完一遍後找到pivot的位置。另外一種是分別從左右兩端出發,最終想匯到partition pivot的位置。
下面的程式是用ruby寫的:
# --------------------------------------------------------------------
# Anthor: Normallife
# Date: 30/3/2013
# --------------------------------------------------------------------
require 'fileUtils'
$outputFile = File.open('result.txt', 'w+')
class QuickSortMethod
# iterate from the left+1 to the right to find the pivot position
def QuickSortMethod.PartitionSecond arrayBeSorted, iBegin, iEnd
if(iBegin < iEnd)
iB = iBegin
iE = iBegin + 1
pivot = arrayBeSorted[iB]
while iE <= iEnd
if arrayBeSorted[iE] < pivot
iB = iB + 1
temp = arrayBeSorted[iB]
arrayBeSorted[iB] = arrayBeSorted[iE]
arrayBeSorted[iE] = temp
end
iE = iE + 1
end
temp = arrayBeSorted[iB]
arrayBeSorted[iB] = arrayBeSorted[iBegin]
arrayBeSorted[iBegin] = temp
return iB
end
return 0
end
# iterate from the left and right to meet at the pivot position
def QuickSortMethod.PartitionFirst arrayBeSorted, iBegin, iEnd
iB = iBegin
iE = iEnd
pivot = arrayBeSorted[iBegin]
while(iB < iE)
while(pivot > arrayBeSorted[iB])
iB = iB + 1
end
while(pivot < arrayBeSorted[iE])
iE = iE - 1
end
temp = arrayBeSorted[iB]
arrayBeSorted[iB] = arrayBeSorted[iE]
arrayBeSorted[iE] = temp
end
#temp = arrayBeSorted[iB]
#arrayBeSorted[iB] = arrayBeSorted[iE]
#arrayBeSorted[iE] = temp
#temp = pivot
#pivot = arrayBeSorted[iE]
#arrayBeSorted[iE] = temp
return iE
end
def QuickSortMethod.TraditionalQuickSort arrayBeSorted, iBegin, iEnd
$outputFile.puts "QuickSort Method begins!!"
arrayBeSorted.each { |v|
$outputFile.puts v.to_s
}
if arrayBeSorted.length == 0
puts "arrayBeSorted is empty array!!"
return false
end
if(iBegin < iEnd)
iPivot = QuickSortMethod.PartitionSecond(arrayBeSorted, iBegin, iEnd)
$outputFile.puts "After one partition, the pivot is number: #{iPivot} "
QuickSortMethod.TraditionalQuickSort(arrayBeSorted, iBegin, iPivot-1)
QuickSortMethod.TraditionalQuickSort(arrayBeSorted, iPivot+1, iEnd)
end
return true
end
end
begin
arrayInQuickSort = Array.[](5, 2, 3, 8, 9, 1, 7)
QuickSortMethod.TraditionalQuickSort(arrayInQuickSort, 0, 6)
p arrayInQuickSort
$outputFile.close()
end