Re: LZ: sorting


[Prev][Next][Index][Thread]

Re: LZ: sorting



On 15 Aug 96 at 13:22, D Melton wrote:


> Does anyone know a short routine to sort a list?  The list is one byte per
> element, one right after the other in memory.  The routine does not
> necessarily have to be that fast, just short.  Thanks for any help.
> 
> -Doug
> http://www.smartlink.net/~dx4/calculat20.html


Bubblesort is very simple and should be enough if it doesn't have to
be fast.


The algorithm is:


 Compare list item 1 and 2
 Put the smallest of them in 1 and the other in 2
 Do the same thing with 2 & 3, 3 & 4 and so on.
 When you reach the end start over with item 1 and 2 again.
 Repeat this cycle until you've gotten through the entire list without
  having to exchange any items. This requires a flag that will be set if
  a pair are changed.


Here's a ZShell routine I wrote a while ago. It can easily be changed 
to fit special purposes, e.g. a fixed number of items or descending 
sort order. Please let me know if you find a way to optimize it.


; --- Bubblesort ---
; Sorts 2-256 byte size elements in ascending order
; Input: HL=Address of list, B=Size of list
; Destroys: C=Change Flag
; Size: 28 bytes


Bubble: 
	PUSH	HL
 	PUSH	BC
 	LD	C,0
 	DEC	B
Loop:
	LD 	A,(HL)
 	INC	HL
 	CP	(HL)
 	JR	C,Forts
 	JR	Z,Forts
 	LD	C,(HL)
 	LD	(HL),A
 	DEC	HL
 	LD	(HL),C
 	INC	HL
 	LD	C,1
 	DEC	C
Forts:
	DJNZ	Loop
 	POP	BC
 	POP	HL
 	RET	NZ
 	JR	Bubble




Regards,
Mattias Lindqvist   <eng96gml@lustudat.student.lu.se>


References: