zweizhao.github.io

项目,文章,随笔,博客,Markdown,个人网站,人生感悟。

View on GitHub
sourceArray = null

sourceArrayReset = ->
	sourceArray = [9,8,7,6,5,4,3,2,1,0]

class Sort
	constructor: (@length) ->
	exchange: (x, y) ->
		sourceArray[x] += sourceArray[y]
		sourceArray[y] = sourceArray[x] - sourceArray[y]
		sourceArray[x] -= sourceArray[y]
	# 冒泡
	bubble: ->
		for i in [0 ... @length]
			for j in [i + 1 .. @length]
				@exchange i, j if sourceArray[i] > sourceArray[j]
		sourceArray
		
	select: ->
		for i in [0 ... @length]
			indexMin = i
			for j in [i + 1 .. @length]
				indexMin = j if sourceArray[indexMin] > sourceArray[j]
			@exchange i, indexMin if i isnt indexMin
		sourceArray
		
	insert: ->
		for i in [1 .. @length]
			j = i
			temp = sourceArray[i]
			while j > 0 and sourceArray[j - 1] > temp
				sourceArray[j] = sourceArray[j - 1]
				j--
			sourceArray[j] = temp
		sourceArray
		
	merge: ->
		mergeIn = (left, right) ->
			result = []
			il = 0
			ir = 0
			while il < left.length and ir < right.length
				if left[il] < right[ir]
					result.push(left[il++])
				else
					result.push(right[ir++])
			result.push(left[il++]) while(il < left.length)
			result.push(right[ir++]) while(ir < right.length)
			result
		
		mergeRec = (array) ->
			if array.length is 1
				return array
			
			mid = Math.floor(array.length / 2)
			left = array.slice(0, mid)
			right = array.slice(mid, array.length)
			mergeIn (mergeRec left), (mergeRec right)
			
		mergeRec(sourceArray)
	
sourceArrayReset()
sort = new Sort(sourceArray.length - 1)

console.log 'bubble: ', sort.bubble()

sourceArrayReset()
console.log 'select: ', sort.select()

sourceArrayReset()
console.log 'insert: ', sort.insert()

sourceArrayReset()
console.log 'merge: ', sort.merge()