Sorting algorithms/Strand sort: Difference between revisions
Implemented Strand Sort in Haskell. |
|||
Line 99: | Line 99: | ||
return result; |
return result; |
||
}</lang> |
}</lang> |
||
=={{header|Common Lisp}}== |
|||
<lang lisp>(defun strand-sort (l cmp) |
|||
(if l |
|||
(let ((o (list (car l))) n) |
|||
(loop for i in (cdr l) do |
|||
(push i (if (funcall cmp i (car o)) n o))) |
|||
(merge 'list |
|||
(reverse o) |
|||
(strand-sort n cmp) #'<)))) |
|||
(let ((r (loop repeat 15 collect (random 10)))) |
|||
(print r) |
|||
(print (strand-sort r #'<)))</lang>output<lang>(5 8 6 0 6 8 4 7 0 7 1 5 3 3 6) |
|||
(0 0 1 3 3 4 5 5 6 6 6 7 7 8 8)</lang> |
|||
=={{header|Euphoria}}== |
=={{header|Euphoria}}== |
||
<lang euphoria>function merge(sequence left, sequence right) |
<lang euphoria>function merge(sequence left, sequence right) |
Revision as of 02:57, 24 October 2011
You are encouraged to solve this task according to the task description, using any language you may know.
Sorting Algorithm
This is a sorting algorithm. It may be applied to a set of data in order to sort it.
For comparing various sorts, see compare sorts.
For other sorting algorithms, see sorting algorithms, or:
Heap sort | Merge sort | Patience sort | Quick sort
O(n log2n) sorts
Shell Sort
O(n2) sorts
Bubble sort |
Cocktail sort |
Cocktail sort with shifting bounds |
Comb sort |
Cycle sort |
Gnome sort |
Insertion sort |
Selection sort |
Strand sort
other sorts
Bead sort |
Bogo sort |
Common sorted list |
Composite structures sort |
Custom comparator sort |
Counting sort |
Disjoint sublist sort |
External sort |
Jort sort |
Lexicographical sort |
Natural sorting |
Order by pair comparisons |
Order disjoint list items |
Order two numerical lists |
Object identifier (OID) sort |
Pancake sort |
Quickselect |
Permutation sort |
Radix sort |
Ranking methods |
Remove duplicate elements |
Sleep sort |
Stooge sort |
[Sort letters of a string] |
Three variable sort |
Topological sort |
Tree sort
This page uses content from Wikipedia. The original article was at Strand sort. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) |
Implement the Strand sort. This is a way of sorting numbers by extracting shorter sequences of already sorted numbers from an unsorted list.
C
Strand sort using singly linked list. C99, compiled with gcc -std=c99
<lang C>#include <stdio.h>
typedef struct node_t *node, node_t; struct node_t { int v; node next; };
void sort(int *ar, int len) { node_t all[len], head, shead, merged, *cur, *next, *stail;
/* linkify */ for (int i = 0; i < len; i++) { all[i].v = ar[i]; all[i].next = all + i + 1; } all[len - 1].next = 0; head.next = all; shead.next = merged.next = 0;
while (head.next) { /* take strand */ cur = &head; stail = shead.next = head.next;
while (next = cur->next) { if (next->v >= stail->v) { cur->next = next->next; stail = stail->next = next; } else cur = next; } stail->next = 0;
/* merge */ cur = merged.next; next = shead.next; stail = &merged;
/* while both lists contain elements, append the smaller one */ while (next && cur) { if (next->v <= cur->v) { stail = stail->next = next; next = next->next; } else { stail = stail->next = cur; cur = cur->next; } } /* append the rest of the survivor to the end of merged */ stail->next = next ? next : cur; } cur = &merged; len = 0; while (cur = cur->next) ar[len++] = cur->v; }
int main() { int x[] = {-2,0,-2,5,5,3,-1,-3,5,5,0,2,-4,4,2};
- define SIZE sizeof(x)/sizeof(int)
printf("before sort:"); for (int i = 0; i < SIZE; i++) printf(" %3d", x[i]);
sort(x, sizeof(x)/sizeof(int));
printf("\nafter sort: "); for (int i = 0; i < SIZE; i++) printf(" %3d", x[i]); printf("\n"); }</lang>outout<lang>before sort: -2 0 -2 5 5 3 -1 -3 5 5 0 2 -4 4 2 after sort: -4 -3 -2 -2 -1 0 0 2 2 3 4 5 5 5 5</lang>
C++
<lang cpp>#include <list>
template <typename T> std::list<T> strandSort(std::list<T> lst) {
if (lst.size() <= 1) return lst; std::list<T> result; std::list<T> sorted; while (!lst.empty()) { sorted.push_back(lst.front()); lst.pop_front(); for (typename std::list<T>::iterator it = lst.begin(); it != lst.end(); ) { if (sorted.back() <= *it) { sorted.push_back(*it); it = lst.erase(it); } else it++; } result.merge(sorted); } return result;
}</lang>
Common Lisp
<lang lisp>(defun strand-sort (l cmp)
(if l (let ((o (list (car l))) n) (loop for i in (cdr l) do
(push i (if (funcall cmp i (car o)) n o)))
(merge 'list
(reverse o) (strand-sort n cmp) #'<))))
(let ((r (loop repeat 15 collect (random 10))))
(print r) (print (strand-sort r #'<)))</lang>output<lang>(5 8 6 0 6 8 4 7 0 7 1 5 3 3 6)
(0 0 1 3 3 4 5 5 6 6 6 7 7 8 8)</lang>
Euphoria
<lang euphoria>function merge(sequence left, sequence right)
sequence result result = {} while length(left) > 0 and length(right) > 0 do if left[$] <= right[1] then exit elsif right[$] <= left[1] then return result & right & left elsif left[1] < right[1] then result = append(result,left[1]) left = left[2..$] else result = append(result,right[1]) right = right[2..$] end if end while return result & left & right
end function
function strand_sort(sequence s)
integer j sequence result result = {} while length(s) > 0 do j = length(s) for i = 1 to length(s)-1 do if s[i] > s[i+1] then j = i exit end if end for result = merge(result,s[1..j]) s = s[j+1..$] end while return result
end function
constant s = rand(repeat(1000,10)) puts(1,"Before: ") ? s puts(1,"After: ") ? strand_sort(s)</lang>
Output:
Before: {551,746,940,903,51,18,346,417,340,502} After: {18,51,340,346,417,502,551,746,903,940}
Go
<lang go>package main
import "fmt"
type link struct {
int next *link
}
func linkInts(s []int) *link {
if len(s) == 0 { return nil } return &link{s[0], linkInts(s[1:])}
}
func (l *link) String() string {
if l == nil { return "nil" } r := fmt.Sprintf("[%d", l.int) for l = l.next; l != nil; l = l.next { r = fmt.Sprintf("%s %d", r, l.int) } return r + "]"
}
func main() {
a := linkInts([]int{170, 45, 75, -90, -802, 24, 2, 66}) fmt.Println("before:", a) b := strandSort(a) fmt.Println("after: ", b)
}
func strandSort(a *link) (result *link) {
for a != nil { // build sublist sublist := a a = a.next sTail := sublist for p, pPrev := a, a; p != nil; p = p.next { if p.int > sTail.int { // append to sublist sTail.next = p sTail = p // remove from a if p == a { a = p.next } else { pPrev.next = p.next } } else { pPrev = p } } sTail.next = nil // terminate sublist if result == nil { result = sublist continue } // merge var m, rr *link if sublist.int < result.int { m = sublist sublist = m.next rr = result } else { m = result rr = m.next } result = m for { if sublist == nil { m.next = rr break } if rr == nil { m.next = sublist break } if sublist.int < rr.int { m.next = sublist m = sublist sublist = m.next } else { m.next = rr m = rr rr = m.next } } } return
}</lang> Output:
before: [170 45 75 -90 -802 24 2 66] after: [-802 -90 2 24 45 66 75 170]
Haskell
<lang haskell>-- Same merge as in Merge Sort merge :: (Ord a) => [a] -> [a] -> [a] merge [] ys = ys merge xs [] = xs merge (x : xs) (y : ys) | x <= y = x : merge xs (y : ys) | otherwise = y : merge (x : xs) ys
strandSort :: (Ord a) => [a] -> [a] strandSort [] = [] strandSort (x : xs) = merge strand (strandSort rest) where (strand, rest) = extractStrand x xs extractStrand x [] = ([x], []) extractStrand x (x1 : xs) | x <= x1 = let (strand, rest) = extractStrand x1 xs in (x : strand, rest) | otherwise = let (strand, rest) = extractStrand x xs in (strand, x1 : rest)</lang>
J
Using merge
defined at Sorting algorithms/Merge sort#J:
<lang j>strandSort=: (#~ merge $:^:(0<#)@(#~ -.)) (= >./\)</lang>
Example use:
<lang j> strandSort 3 1 5 4 2 1 2 3 4 5</lang>
Note: the order in which this J implementation processes the strands differs from the pseudocode currently at the wikipedia page on strand sort and matches the haskell implementation currently at the wikipedia page.
Also note that the individual strands can be seen by using ;
instead of merge
.
<lang j> ((#~ ; $:^:(0<#)@(#~ -.)) (= >./\)) 3 1 5 4 2 ┌───┬───┬─┬┐ │3 5│1 4│2││ └───┴───┴─┴┘
((#~ ; $:^:(0<#)@(#~ -.)) (= >./\)) 3 3 1 2 4 3 5 6
┌─────────┬─────┬┐ │3 3 4 5 6│1 2 3││ └─────────┴─────┴┘</lang>
Java
<lang java5>import java.util.Arrays; import java.util.LinkedList;
public class Strand{ // note: the input list is destroyed public static <E extends Comparable<? super E>> LinkedList<E> strandSort(LinkedList<E> list){ if(list.size() <= 1) return list;
LinkedList<E> result = new LinkedList<E>(); while(list.size() > 0){ LinkedList<E> sorted = new LinkedList<E>(); sorted.add(list.removeFirst()); //same as remove() or remove(0) for(Iterator<E> it = list.iterator(); it.hasNext(); ){ E elem = it.next(); if(sorted.peekLast().compareTo(elem) <= 0){ sorted.addLast(elem); //same as add(elem) or add(0, elem) it.remove(); } } result = merge(sorted, result); } return result; }
private static <E extends Comparable<? super E>> LinkedList<E> merge(LinkedList<E> left, LinkedList<E> right){ LinkedList<E> result = new LinkedList<E>(); while(!left.isEmpty() && !right.isEmpty()){ //change the direction of this comparison to change the direction of the sort if(left.peek().compareTo(right.peek()) <= 0) result.add(left.remove()); else result.add(right.remove()); } result.addAll(left); result.addAll(right); return result; }
public static void main(String[] args){ System.out.println(strandSort(new LinkedList<Integer>(Arrays.asList(3,1,2,4,5)))); System.out.println(strandSort(new LinkedList<Integer>(Arrays.asList(3,3,1,2,4,5)))); System.out.println(strandSort(new LinkedList<Integer>(Arrays.asList(3,3,1,2,4,3,5,6)))); } }</lang> Output:
[1, 2, 3, 4, 5] [1, 2, 3, 3, 4, 5] [1, 2, 3, 3, 3, 4, 5, 6]
NetRexx
<lang NetRexx>/* NetRexx */ options replace format comments java crossref savelog symbols binary
import java.util.List
placesList = [String -
"UK London", "US New York", "US Boston", "US Washington" - , "UK Washington", "US Birmingham", "UK Birmingham", "UK Boston" -
]
lists = [ -
placesList - , strandSort(String[] Arrays.copyOf(placesList, placesList.length)) -
]
loop ln = 0 to lists.length - 1
cl = lists[ln] loop ct = 0 to cl.length - 1 say cl[ct] end ct say end ln
return
method strandSort(A = String[]) public constant binary returns String[]
rl = String[A.length] al = List strandSort(Arrays.asList(A)) al.toArray(rl)
return rl
method strandSort(Alst = List) public constant binary returns ArrayList
A = ArrayList(Alst) result = ArrayList() loop label A_ while A.size > 0 sublist = ArrayList() sublist.add(A.get(0)) A.remove(0) loop i_ = 0 while i_ < A.size - 1 if (Comparable A.get(i_)).compareTo(Comparable sublist.get(sublist.size - 1)) > 0 then do sublist.add(A.get(i_)) A.remove(i_) end end i_ result = merge(result, sublist) end A_
return result
method merge(left = List, right = List) public constant binary returns ArrayList
result = ArrayList() loop label mx while left.size > 0 & right.size > 0 if (Comparable left.get(0)).compareTo(Comparable right.get(0)) <= 0 then do result.add(left.get(0)) left.remove(0) end else do result.add(right.get(0)) right.remove(0) end end mx if left.size > 0 then do result.addAll(left) end if right.size > 0 then do result.addAll(right) end
return result
</lang>
- Output
UK London US New York US Boston US Washington UK Washington US Birmingham UK Birmingham UK Boston UK Birmingham UK Boston UK London UK Washington US Birmingham US Boston US New York US Washington
PARI/GP
<lang parigp>strandSort(v)={ my(sorted=[],unsorted=v,remaining,working); while(#unsorted, remaining=working=List(); listput(working, unsorted[1]); for(i=2,#unsorted, if(unsorted[i]<working[#working], listput(remaining, unsorted[i]) , listput(working, unsorted[i]) ) ); unsorted=Vec(remaining); sorted=merge(sorted, Vec(working)) ); sorted }; merge(u,v)={ my(ret=vector(#u+#v),i=1,j=1); for(k=1,#ret, if(i<=#u & (j>#v | u[i]<v[j]), ret[k]=u[i]; i++ , ret[k]=v[j]; j++ ) ); ret };</lang>
Perl
<lang Perl>use 5.10.0; # for given/when sub merge {
my ($x, $y) = @_; my @out; while (@$x and @$y) { given ($x->[-1] <=> $y->[-1]) { when( 1) { unshift @out, pop @$x } when(-1) { unshift @out, pop @$y } default { splice @out, 0, 0, pop(@$x), pop(@$y) } } } return @$x, @$y, @out
}
sub strand {
my $x = shift; my @out = shift @$x // return; if (@$x) { for (-@$x .. -1) { if ($x->[$_] >= $out[-1]) { push @out, splice @$x, $_, 1 } } } return @out
}
sub strand_sort {
my @x = @_; my @out; while (my @strand = strand(\@x)) { @out = merge(\@out, \@strand) } @out
}
my @a = map (int rand(100), 1 .. 10); say "Before @a"; @a = strand_sort(@a); say "After @a";</lang>
PicoLisp
<lang PicoLisp>(de strandSort (Lst)
(let Res NIL # Result list (while Lst (let Sub (circ (car Lst)) # Build sublist as fifo (setq Lst (filter '((X) (or (> (car Sub) X) (nil (fifo 'Sub X)) ) ) (cdr Lst) ) Res (make (while (or Res Sub) # Merge (link (if2 Res Sub (if (>= (car Res) (cadr Sub)) (fifo 'Sub) (pop 'Res) ) (pop 'Res) (fifo 'Sub) ) ) ) ) ) ) ) Res ) )</lang>
Test:
: (strandSort (3 1 5 4 2)) -> (1 2 3 4 5) : (strandSort (3 abc 1 (d e f) 5 T 4 NIL 2)) -> (NIL 1 2 3 4 5 abc (d e f) T)
PureBasic
<lang PureBasic>Procedure strandSort(List a())
Protected NewList subList() Protected NewList results() While ListSize(a()) > 0 ClearList(subList()) AddElement(subList()) FirstElement(a()) subList() = a() DeleteElement(a()) ForEach a() If a() >= subList() AddElement(subList()) subList() = a() DeleteElement(a()) EndIf Next ;merge lists FirstElement(subList()) If Not FirstElement(results()) ;copy all of sublist() to results() MergeLists(subList(), results(), #PB_List_Last) Else Repeat If subList() < results() InsertElement(results()) results() = subList() DeleteElement(subList()) If Not NextElement(subList()) Break EndIf ElseIf Not NextElement(results()) ;add remainder of sublist() to end of results() MergeLists(subList(), results(), #PB_List_Last) Break EndIf ForEver EndIf Wend CopyList(results(), a())
EndProcedure
Procedure.s listContents(List a())
Protected output.s PushListPosition(a()) ForEach a() output + Str(a()) + "," Next PopListPosition(a()) ProcedureReturn Left(output, Len(output) - 1)
EndProcedure
Procedure setupList(List a())
ClearList(a()) Protected elementCount, i elementCount = Random(5) + 10 For i = 1 To elementCount AddElement(a()) a() = Random(10) - 5 Next
EndProcedure
If OpenConsole()
NewList sample() Define i For i = 1 To 3 setupList(sample()) PrintN("List " + Str(i) + ":") PrintN(" Before: " + listContents(sample())) strandSort(sample()) PrintN(" After : " + listContents(sample())) PrintN("") Next Print(#CRLF$ + #CRLF$ + "Press ENTER to exit"): Input() CloseConsole()
EndIf</lang> Sample output:
List 1: Before: 3,-2,-4,4,-1,-3,-2,-2,2,2,0 After : -4,-3,-2,-2,-2,-1,0,2,2,3,4 List 2: Before: -4,4,3,-2,3,-2,5,0,-1,0,5,1 After : -4,-2,-2,-1,0,0,1,3,3,4,5,5 List 3: Before: -2,0,-2,5,5,3,-1,-3,5,5,0,2,-4,4,2 After : -4,-3,-2,-2,-1,0,0,2,2,3,4,5,5,5,5
Python
<lang Python>def merge_list(a, b): out = [] while len(a) and len(b): if a[0] < b[0]: out.append(a.pop(0)) else: out.append(b.pop(0)) out[len(out):] = a out[len(out):] = b return out
def strand(a): i, s = 0, [a.pop(0)] while i < len(a): if a[i] > s[-1]: s.append(a.pop(i)) else: i = i + 1 return s
def strand_sort(a): out = strand(a) while len(a): out = merge_list(out, strand(a)) return out
print strand_sort([1, 6, 3, 2, 1, 7, 5, 3])</lang> Output:<lang>[1, 1, 2, 3, 3, 5, 6, 7]</lang>
Tcl
<lang tcl>proc merge {listVar toMerge} {
upvar 1 $listVar v set i [set j 0] set out {} while {$i<[llength $v] && $j<[llength $toMerge]} {
if {[set a [lindex $v $i]] < [set b [lindex $toMerge $j]]} { lappend out $a incr i } else { lappend out $b incr j }
} # Done the merge, but will be one source with something left # This will handle all that by doing a merge of the remnants onto the end set v [concat $out [lrange $v $i end] [lrange $toMerge $j end]] return
}
proc strandSort A {
set results {} while {[llength $A]} {
set sublist [lrange $A 0 0] # We build a list of items that weren't filtered rather than removing "in place" # because this fits better with the way Tcl values work (the underlying data # structure is an array, not a linked list). set newA {} foreach a [lrange $A 1 end] { if {$a > [lindex $sublist end]} { lappend sublist $a } else { lappend newA $a } } set A $newA merge results $sublist
} return $results
}
puts [strandSort {3 1 5 4 2}]</lang>
Ursala
<lang Ursala>strand_sort "r" = # parameterized by a relational predicate "r"
@NiX -+
:-0 ~&B^?a\~&Y@a "r"?abh/~&alh2faltPrXPRC ~&arh2falrtPXPRC, ~&r->l ^|rlPlCrrPX/~& @hNCNXtX ~&r->lbx "r"?rllPXh/~&llPrhPlrPCXrtPX ~&rhPllPClrPXrtPX+-</lang>
demonstration code:<lang Ursala>#cast %nL
x = (strand_sort nat-nleq) <3,1,5,4,2></lang>output:
<1,2,3,4,5>