task_url
stringlengths 30
116
| task_name
stringlengths 2
86
| task_description
stringlengths 0
14.4k
| language_url
stringlengths 2
53
| language_name
stringlengths 1
52
| code
stringlengths 0
61.9k
|
---|---|---|---|---|---|
http://rosettacode.org/wiki/Singly-linked_list/Element_insertion | Singly-linked list/Element insertion | Singly-Linked List (element)
singly-linked list
Using this method, insert an element C into a list comprised of elements A->B, following element A.
See also
Array
Associative array: Creation, Iteration
Collections
Compound data type
Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal
Linked list
Queue: Definition, Usage
Set
Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal
Stack
| #Clojure | Clojure | (defn insert-after [new old ls]
(cond (empty? ls) ls
(= (first ls) old) (cons old (cons new (rest ls)))
:else (cons (first ls) (insert-after new old (rest ls))))) |
http://rosettacode.org/wiki/Sleep | Sleep | Task
Write a program that does the following in this order:
Input an amount of time to sleep in whatever units are most natural for your language (milliseconds, seconds, ticks, etc.). This unit should be noted in comments or in a description.
Print "Sleeping..."
Sleep the main thread for the given amount of time.
Print "Awake!"
End.
Related task
Nautical bell
| #BASIC | BASIC | INPUT sec 'the SLEEP command takes seconds
PRINT "Sleeping..."
SLEEP sec
PRINT "Awake!" |
http://rosettacode.org/wiki/Sleep | Sleep | Task
Write a program that does the following in this order:
Input an amount of time to sleep in whatever units are most natural for your language (milliseconds, seconds, ticks, etc.). This unit should be noted in comments or in a description.
Print "Sleeping..."
Sleep the main thread for the given amount of time.
Print "Awake!"
End.
Related task
Nautical bell
| #Batch_File | Batch File | @echo off
set /p Seconds=Enter the number of seconds to sleep:
set /a Seconds+=1
echo Sleeping ...
ping -n %Seconds% localhost >nul 2>&1
echo Awake! |
http://rosettacode.org/wiki/Sorting_algorithms/Bubble_sort | Sorting algorithms/Bubble sort |
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:
O(n logn) sorts
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
A bubble sort is generally considered to be the simplest sorting algorithm.
A bubble sort is also known as a sinking sort.
Because of its simplicity and ease of visualization, it is often taught in introductory computer science courses.
Because of its abysmal O(n2) performance, it is not used often for large (or even medium-sized) datasets.
The bubble sort works by passing sequentially over a list, comparing each value to the one immediately after it. If the first value is greater than the second, their positions are switched. Over a number of passes, at most equal to the number of elements in the list, all of the values drift into their correct positions (large values "bubble" rapidly toward the end, pushing others down around them).
Because each pass finds the maximum item and puts it at the end, the portion of the list to be sorted can be reduced at each pass.
A boolean variable is used to track whether any changes have been made in the current pass; when a pass completes without changing anything, the algorithm exits.
This can be expressed in pseudo-code as follows (assuming 1-based indexing):
repeat
if itemCount <= 1
return
hasChanged := false
decrement itemCount
repeat with index from 1 to itemCount
if (item at index) > (item at (index + 1))
swap (item at index) with (item at (index + 1))
hasChanged := true
until hasChanged = false
Task
Sort an array of elements using the bubble sort algorithm. The elements must have a total order and the index of the array can be of any discrete type. For languages where this is not possible, sort an array of integers.
References
The article on Wikipedia.
Dance interpretation.
| #Symsyn | Symsyn |
x : 23 : 15 : 99 : 146 : 3 : 66 : 71 : 5 : 23 : 73 : 19
bubble_sort param index size
+ index size limit
lp
changes
- limit
index i
if i < limit
+ 1 i ip1
if base.i > base.ip1
swap base.i base.ip1
+ changes
endif
+ i
goif
endif
if changes > 0
go lp
endif
return
start
' original values : ' $r
call showvalues
call bubble_sort @x #x
' sorted values : ' $r
call showvalues
stop
showvalues
$s
i
if i < #x
"$s ' ' x.i ' '" $s
+ i
goif
endif
" $r $s " []
return
|
http://rosettacode.org/wiki/Singly-linked_list/Element_definition | Singly-linked list/Element definition | singly-linked list
See also
Array
Associative array: Creation, Iteration
Collections
Compound data type
Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal
Linked list
Queue: Definition, Usage
Set
Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal
Stack | #Go | Go | type Ele struct {
Data interface{}
Next *Ele
}
func (e *Ele) Append(data interface{}) *Ele {
if e.Next == nil {
e.Next = &Ele{data, nil}
} else {
tmp := &Ele{data, e.Next}
e.Next = tmp
}
return e.Next
}
func (e *Ele) String() string {
return fmt.Sprintf("Ele: %v", e.Data)
} |
http://rosettacode.org/wiki/Singly-linked_list/Element_definition | Singly-linked list/Element definition | singly-linked list
See also
Array
Associative array: Creation, Iteration
Collections
Compound data type
Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal
Linked list
Queue: Definition, Usage
Set
Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal
Stack | #Groovy | Groovy | class ListNode {
Object payload
ListNode next
String toString() { "${payload} -> ${next}" }
} |
http://rosettacode.org/wiki/Singly-linked_list/Traversal | Singly-linked list/Traversal | Traverse from the beginning of a singly-linked list to the end.
See also
Array
Associative array: Creation, Iteration
Collections
Compound data type
Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal
Linked list
Queue: Definition, Usage
Set
Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal
Stack
| #EchoLisp | EchoLisp |
(define friends '( albert ludwig elvis 🌀))
(for-each write friends)→ albert ludwig elvis 🌀
; for loop
(for ((friend friends)) (write friend)) → albert ludwig elvis 🌀
; map a function
(map string-upcase friends) → ("ALBERT" "LUDWIG" "ELVIS" "🌀")
(map string-randcase friends) → ("ALBerT" "LudWIG" "elVis" "🌀")
; recursive way
(define (rscan L)
(unless (null? L)
(write (first L))
(rscan (rest L))))
(rscan friends) → albert ludwig elvis 🌀
; folding a list
; check that ∑ 1..n = n (n+1)/2
(define L (iota 1001))
(foldl + 0 L) → 500500 ; 1000 * 1001 / 2
|
http://rosettacode.org/wiki/Singly-linked_list/Element_insertion | Singly-linked list/Element insertion | Singly-Linked List (element)
singly-linked list
Using this method, insert an element C into a list comprised of elements A->B, following element A.
See also
Array
Associative array: Creation, Iteration
Collections
Compound data type
Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal
Linked list
Queue: Definition, Usage
Set
Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal
Stack
| #Common_Lisp | Common Lisp | (defun insert-after (new-element old-element list &key (test 'eql))
"Return a list like list, but with new-element appearing after the
first occurence of old-element. If old-element does not appear in
list, then a list returning just new-element is returned."
(if (endp list) (list new-element)
(do ((head (list (first list)) (cons (first tail) head))
(tail (rest list) (rest tail)))
((or (endp tail) (funcall test old-element (first head)))
(nreconc head (cons new-element tail))))))
(defun ninsert-after (new-element old-element list &key (test 'eql))
"Like insert-after, but modifies list in place. If list is empty, a
new list containing just new-element is returned."
(if (endp list) (list new-element)
(do ((prev list next)
(next (cdr list) (cdr next)))
((or (null next) (funcall test old-element (car prev)))
(rplacd prev (cons new-element next))
list)))) |
http://rosettacode.org/wiki/Sleep | Sleep | Task
Write a program that does the following in this order:
Input an amount of time to sleep in whatever units are most natural for your language (milliseconds, seconds, ticks, etc.). This unit should be noted in comments or in a description.
Print "Sleeping..."
Sleep the main thread for the given amount of time.
Print "Awake!"
End.
Related task
Nautical bell
| #BBC_BASIC | BBC BASIC | INPUT "Enter the time to sleep in centiseconds: " sleep%
PRINT "Sleeping..."
WAIT sleep%
PRINT "Awake!" |
http://rosettacode.org/wiki/Sleep | Sleep | Task
Write a program that does the following in this order:
Input an amount of time to sleep in whatever units are most natural for your language (milliseconds, seconds, ticks, etc.). This unit should be noted in comments or in a description.
Print "Sleeping..."
Sleep the main thread for the given amount of time.
Print "Awake!"
End.
Related task
Nautical bell
| #C | C | #include <stdio.h>
#include <unistd.h>
int main()
{
unsigned int seconds;
scanf("%u", &seconds);
printf("Sleeping...\n");
sleep(seconds);
printf("Awake!\n");
return 0;
} |
http://rosettacode.org/wiki/Sorting_algorithms/Bubble_sort | Sorting algorithms/Bubble sort |
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:
O(n logn) sorts
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
A bubble sort is generally considered to be the simplest sorting algorithm.
A bubble sort is also known as a sinking sort.
Because of its simplicity and ease of visualization, it is often taught in introductory computer science courses.
Because of its abysmal O(n2) performance, it is not used often for large (or even medium-sized) datasets.
The bubble sort works by passing sequentially over a list, comparing each value to the one immediately after it. If the first value is greater than the second, their positions are switched. Over a number of passes, at most equal to the number of elements in the list, all of the values drift into their correct positions (large values "bubble" rapidly toward the end, pushing others down around them).
Because each pass finds the maximum item and puts it at the end, the portion of the list to be sorted can be reduced at each pass.
A boolean variable is used to track whether any changes have been made in the current pass; when a pass completes without changing anything, the algorithm exits.
This can be expressed in pseudo-code as follows (assuming 1-based indexing):
repeat
if itemCount <= 1
return
hasChanged := false
decrement itemCount
repeat with index from 1 to itemCount
if (item at index) > (item at (index + 1))
swap (item at index) with (item at (index + 1))
hasChanged := true
until hasChanged = false
Task
Sort an array of elements using the bubble sort algorithm. The elements must have a total order and the index of the array can be of any discrete type. For languages where this is not possible, sort an array of integers.
References
The article on Wikipedia.
Dance interpretation.
| #Tailspin | Tailspin |
templates bubblesort
templates bubble
@: 1;
1..$-1 -> #
$@ !
when <?($@bubblesort($+1) <..~$@bubblesort($)>)> do
@: $;
def temp: $@bubblesort($@);
@bubblesort($@): $@bubblesort($@+1);
@bubblesort($@+1): $temp;
end bubble
@: $;
$::length -> #
$@ !
when <2..> do
$ -> bubble -> #
end bubblesort
[4,5,3,8,1,2,6,7,9,8,5] -> bubblesort -> !OUT::write
|
http://rosettacode.org/wiki/Singly-linked_list/Element_definition | Singly-linked list/Element definition | singly-linked list
See also
Array
Associative array: Creation, Iteration
Collections
Compound data type
Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal
Linked list
Queue: Definition, Usage
Set
Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal
Stack | #Haskell | Haskell | data List a = Nil | Cons a (List a) |
http://rosettacode.org/wiki/Singly-linked_list/Element_definition | Singly-linked list/Element definition | singly-linked list
See also
Array
Associative array: Creation, Iteration
Collections
Compound data type
Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal
Linked list
Queue: Definition, Usage
Set
Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal
Stack | #Icon_and_Unicon | Icon and Unicon |
record Node (value, successor)
|
http://rosettacode.org/wiki/Singly-linked_list/Traversal | Singly-linked list/Traversal | Traverse from the beginning of a singly-linked list to the end.
See also
Array
Associative array: Creation, Iteration
Collections
Compound data type
Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal
Linked list
Queue: Definition, Usage
Set
Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal
Stack
| #Ela | Ela | traverse [] = []
traverse (x::xs) = x :: traverse xs |
http://rosettacode.org/wiki/Singly-linked_list/Traversal | Singly-linked list/Traversal | Traverse from the beginning of a singly-linked list to the end.
See also
Array
Associative array: Creation, Iteration
Collections
Compound data type
Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal
Linked list
Queue: Definition, Usage
Set
Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal
Stack
| #Elena | Elena |
while(nil != current){
console printLine(current.Item);
current := current.Next
} |
http://rosettacode.org/wiki/Singly-linked_list/Element_insertion | Singly-linked list/Element insertion | Singly-Linked List (element)
singly-linked list
Using this method, insert an element C into a list comprised of elements A->B, following element A.
See also
Array
Associative array: Creation, Iteration
Collections
Compound data type
Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal
Linked list
Queue: Definition, Usage
Set
Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal
Stack
| #D | D | struct SLinkedNode(T) {
T data;
typeof(this)* next;
}
void insertAfter(T)(SLinkedNode!T* listNode, SLinkedNode!T* newNode) {
newNode.next = listNode.next;
listNode.next = newNode;
}
void main() {
alias N = SLinkedNode!char;
auto lh = new N('A', new N('B'));
auto c = new N('C');
// Inserts C after A, creating the (A C B) list:
insertAfter(lh, c);
// The GC will collect the memory.
} |
http://rosettacode.org/wiki/Singly-linked_list/Element_insertion | Singly-linked list/Element insertion | Singly-Linked List (element)
singly-linked list
Using this method, insert an element C into a list comprised of elements A->B, following element A.
See also
Array
Associative array: Creation, Iteration
Collections
Compound data type
Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal
Linked list
Queue: Definition, Usage
Set
Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal
Stack
| #Delphi | Delphi | // Using the same type defs from the one way list example.
Type
// The pointer to the list structure
pOneWayList = ^OneWayList;
// The list structure
OneWayList = record
pData : pointer ;
Next : pOneWayList ;
end;
// I will illustrate a simple function that will return a pointer to the
// new node or it will return NIL. In this example I will always insert
// right, to keep the code clear. Since I am using a function all operations
// for the new node will be conducted on the functions result. This seems
// somewhat counter intuitive, but it is the simplest way to accomplish this.
Function InsertNode(VAR CurrentNode:pOneWayList): pOneWayList
begin
// I try not to introduce different parts of the language, and keep each
// example to just the code required. in this case it is important to use
// a try/except block. In any OS that is multi-threaded and has many apps
// running at the same time, you cannot rely on a call to check memory available
// and then attempting to allocate. In the time between the two, another
// program may have grabbed the memory you were trying to get.
Try
// Try to allocate enough memory for a variable the size of OneWayList
GetMem(Result,SizeOf(OneWayList));
Except
On EOutOfMemoryError do
begin
Result := NIL
exit;
end;
end;
// Initialize the variable.
Result.Next := NIL ;
Reuslt.pdata := NIL ;
// Ok now we will insert to the right.
// Is the Next pointer of CurrentNode Nil? If it is we are just tacking
// on to the end of the list.
if CurrentNode.Next = NIL then
CurrentNode.Next := Result
else
// We are inserting into the middle of this list
Begin
Result.Next := CurrentNode.Next ;
CurrentNode.Next := result ;
end;
end; |
http://rosettacode.org/wiki/Sleep | Sleep | Task
Write a program that does the following in this order:
Input an amount of time to sleep in whatever units are most natural for your language (milliseconds, seconds, ticks, etc.). This unit should be noted in comments or in a description.
Print "Sleeping..."
Sleep the main thread for the given amount of time.
Print "Awake!"
End.
Related task
Nautical bell
| #C.23 | C# | using System;
using System.Threading;
class Program
{
static void Main(string[] args)
{
int sleep = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Sleeping...");
Thread.Sleep(sleep); //milliseconds
Console.WriteLine("Awake!");
}
} |
http://rosettacode.org/wiki/Sorting_algorithms/Bubble_sort | Sorting algorithms/Bubble sort |
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:
O(n logn) sorts
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
A bubble sort is generally considered to be the simplest sorting algorithm.
A bubble sort is also known as a sinking sort.
Because of its simplicity and ease of visualization, it is often taught in introductory computer science courses.
Because of its abysmal O(n2) performance, it is not used often for large (or even medium-sized) datasets.
The bubble sort works by passing sequentially over a list, comparing each value to the one immediately after it. If the first value is greater than the second, their positions are switched. Over a number of passes, at most equal to the number of elements in the list, all of the values drift into their correct positions (large values "bubble" rapidly toward the end, pushing others down around them).
Because each pass finds the maximum item and puts it at the end, the portion of the list to be sorted can be reduced at each pass.
A boolean variable is used to track whether any changes have been made in the current pass; when a pass completes without changing anything, the algorithm exits.
This can be expressed in pseudo-code as follows (assuming 1-based indexing):
repeat
if itemCount <= 1
return
hasChanged := false
decrement itemCount
repeat with index from 1 to itemCount
if (item at index) > (item at (index + 1))
swap (item at index) with (item at (index + 1))
hasChanged := true
until hasChanged = false
Task
Sort an array of elements using the bubble sort algorithm. The elements must have a total order and the index of the array can be of any discrete type. For languages where this is not possible, sort an array of integers.
References
The article on Wikipedia.
Dance interpretation.
| #Tcl | Tcl | package require Tcl 8.5
package require struct::list
proc bubblesort {A} {
set len [llength $A]
set swapped true
while {$swapped} {
set swapped false
for {set i 0} {$i < $len - 1} {incr i} {
set j [expr {$i + 1}]
if {[lindex $A $i] > [lindex $A $j]} {
struct::list swap A $i $j
set swapped true
}
}
incr len -1
}
return $A
}
puts [bubblesort {8 6 4 2 1 3 5 7 9}] ;# => 1 2 3 4 5 6 7 8 9 |
http://rosettacode.org/wiki/Singly-linked_list/Element_definition | Singly-linked list/Element definition | singly-linked list
See also
Array
Associative array: Creation, Iteration
Collections
Compound data type
Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal
Linked list
Queue: Definition, Usage
Set
Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal
Stack | #J | J | list=: 0 2$0
list |
http://rosettacode.org/wiki/Singly-linked_list/Element_definition | Singly-linked list/Element definition | singly-linked list
See also
Array
Associative array: Creation, Iteration
Collections
Compound data type
Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal
Linked list
Queue: Definition, Usage
Set
Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal
Stack | #Java | Java | class Link
{
Link next;
int data;
} |
http://rosettacode.org/wiki/Simple_windowed_application | Simple windowed application | Task
Create a window that has:
a label that says "There have been no clicks yet"
a button that says "click me"
Upon clicking the button with the mouse, the label should change and show the number of times the button has been clicked.
| #AArch64_Assembly | AArch64 Assembly |
/* ARM assembly AARCH64 Raspberry PI 3B */
/* program simpleWin64.s link with X11 library */
/*******************************************/
/* Constantes file */
/*******************************************/
/* for this file see task include a file in language AArch64 assembly*/
.include "../includeConstantesARM64.inc"
/* constantes X11 */
.equ KeyPressed, 2
.equ ButtonPress, 4
.equ ClientMessage, 33
.equ KeyPressMask, 1
.equ ButtonPressMask, 4
.equ ButtonReleaseMask, 8
.equ ExposureMask, 1<<15
.equ StructureNotifyMask, 1<<17
.equ EnterWindowMask, 1<<4
.equ LeaveWindowMask, 1<<5
/*******************************************/
/* Structures */
/********************************************/
/* Button structure */
.struct 0
BT_cbdata:
.struct BT_cbdata + 8
BT_adresse:
.struct BT_adresse + 8
BT_GC:
.struct BT_GC + 8
BT_Font:
.struct BT_Font + 8
BT_fin:
/***************************************************/
/* structure XButtonEvent */
.struct 0
XBE_type: //event type
.struct XBE_type + 8
XBE_serial: // No last request processed server */
.struct XBE_serial + 8
XBE_send_event: // true if this came from a SendEvent request */
.struct XBE_send_event + 8
XBE_display: // Display the event was read from
.struct XBE_display + 8
XBE_window: // "event" window it is reported relative to
.struct XBE_window + 8
XBE_root: // root window that the event occurred on
.struct XBE_root + 8
XBE_subwindow: // child window
.struct XBE_subwindow + 8
XBE_time: // milliseconds
.struct XBE_time + 8
XBE_x: // pointer x, y coordinates in event window
.struct XBE_x + 8
XBE_y:
.struct XBE_y + 8
XBE_x_root: // coordinates relative to root
.struct XBE_x_root + 8
XBE_y_root:
.struct XBE_y_root + 8
XBE_state: // key or button mask
.struct XBE_state + 8
XBE_button: // detail
.struct XBE_button + 8
XBE_same_screen: // same screen flag
.struct XBE_same_screen + 8
XBE_fin:
/*******************************************/
/* Initialized data */
/*******************************************/
.data
szRetourligne: .asciz "\n"
szMessErreur: .asciz "Server X11 not found.\n"
szMessErrfen: .asciz "Error create X11 window.\n"
szMessErrGC: .asciz "Error create Graphic Context.\n"
szMessErrButton: .asciz "Error create button.\n"
szMessErrButtonGC: .asciz "Error create button Graphic Context.\n"
szMessGoodBye: .asciz "There have been no clicks yet"
szTextButton: .asciz "Click me"
szMessResult: .asciz "You clicked me @ times "
szLibDW: .asciz "WM_DELETE_WINDOW" // message close window
/*******************************************/
/* UnInitialized data */
/*******************************************/
.bss
.align 4
qDisplay: .skip 8 // Display address
qDefScreen: .skip 8 // Default screen address
identWin: .skip 8 // window ident
qCounterClic: .skip 8 // counter clic button
sZoneConv: .skip 24
wmDeleteMessage: .skip 16 // ident close message
stEvent: .skip 400 // provisional size
stButton: .skip BT_fin
buffer: .skip 500
/**********************************************/
/* -- Code section */
/**********************************************/
.text
.global main // program entry
main:
mov x0,#0 // open server X
bl XOpenDisplay
cmp x0,#0
beq erreur
// Ok return Display address
ldr x1,qAdrqDisplay
str x0,[x1] // store Display address for future use
mov x28,x0 // and in register 28
// load default screen
ldr x2,[x0,#264] // at location 264
ldr x1,qAdrqDefScreen
str x2,[x1] //store default_screen
mov x2,x0
ldr x0,[x2,#232] // screen list
//screen areas
ldr x5,[x0,#+88] // white pixel
ldr x3,[x0,#+96] // black pixel
ldr x4,[x0,#+56] // bits par pixel
ldr x1,[x0,#+16] // root windows
// create window x11
mov x0,x28 //display
mov x2,#0 // position X
mov x3,#0 // position Y
mov x4,600 // weight
mov x5,400 // height
mov x6,0 // bordure ???
ldr x7,0 // ?
ldr x8,qBlanc // background
str x8,[sp,-16]! // argument fot stack
bl XCreateSimpleWindow
add sp,sp,16 // for stack alignement
cmp x0,#0 // error ?
beq erreurF
ldr x1,qAdridentWin
str x0,[x1] // store window ident for future use
mov x27,x0 // and in register 27
// Correction of window closing error
mov x0,x28 // Display address
ldr x1,qAdrszLibDW // atom name address
mov x2,#1 // False create atom if not exist
bl XInternAtom
cmp x0,#0
ble erreurF
ldr x1,qAdrwmDeleteMessage // address message
str x0,[x1]
mov x2,x1 // address atom create
mov x0,x28 // display address
mov x1,x27 // window ident
mov x3,#1 // number of protocoles
bl XSetWMProtocols
cmp x0,#0
ble erreurF
// authorization of seizures
mov x0,x28 // display address
mov x1,x27 // window ident
ldr x2,qFenetreMask // mask
bl XSelectInput
cmp x0,#0
ble 99f
// create Graphic Context
mov x0,x28 // display address
mov x1,x27 // window ident
bl createGC // GC address -> x26
cbz x0,erreurF
// create Graphic Context 1
mov x0,x28 // display address
mov x1,x27 // window ident
bl createGC1 // GC address -> x25
cbz x0,erreurF
// Display window
mov x1,x27 // ident window
mov x0,x28 // Display address
bl XMapWindow
ldr x0,qAdrszMessGoodBye // display text
bl displayText
bl createButton // create button on screen
1: // events loop
mov x0,x28 // Display address
ldr x1,qAdrstEvent // events structure address
bl XNextEvent
ldr x0,qAdrstEvent // events structure address
ldr w0,[x0] // type in 4 first bytes
cmp w0,#ClientMessage // message for close window
beq 2f // yes -> end
cmp w0,#ButtonPress // clic mouse button
beq 3f
// other events
b 1b // and loop
2:
ldr x0,qAdrstEvent // events structure address
ldr x1,[x0,56] // location message code
ldr x2,qAdrwmDeleteMessage // equal ?
ldr x2,[x2]
cmp x1,x2
bne 1b // no loop
mov x0,0 // end Ok
b 100f
//TODO: close ??
3:
ldr x0,qAdrstEvent // events structure address
bl evtButtonMouse
b 1b
erreurF: // error create window
ldr x0,qAdrszMessErrfen
bl affichageMess
mov x0,1
b 100f
erreur: // error no server x11 active
ldr x0,qAdrszMessErreur
bl affichageMess
mov x0,1
100: // program standard end
mov x8,EXIT
svc 0
qBlanc: .quad 0xF0F0F0F0
qAdrqDisplay: .quad qDisplay
qAdrqDefScreen: .quad qDefScreen
qAdridentWin: .quad identWin
qAdrstEvent: .quad stEvent
qAdrszMessErrfen: .quad szMessErrfen
qAdrszMessErreur: .quad szMessErreur
qAdrwmDeleteMessage: .quad wmDeleteMessage
qAdrszLibDW: .quad szLibDW
qAdrszMessGoodBye: .quad szMessGoodBye
qFenetreMask: .quad KeyPressMask|ButtonPressMask|StructureNotifyMask|ExposureMask|EnterWindowMask
/******************************************************************/
/* create Graphic Context */
/******************************************************************/
/* x0 contains the Display address */
/* x1 contains the ident Window */
createGC:
stp x20,lr,[sp,-16]! // save registers
mov x20,x0 // save display address
mov x2,#0
mov x3,#0
bl XCreateGC
cbz x0,99f
mov x26,x0 // save GC
mov x0,x20 // display address
mov x1,x26
ldr x2,qRed // code RGB color
bl XSetForeground
cbz x0,99f
mov x0,x26 // return GC
b 100f
99:
ldr x0,qAdrszMessErrGC
bl affichageMess
mov x0,0
100:
ldp x20,lr,[sp],16 // restaur 2 registers
ret // return to address lr x30
qAdrszMessErrGC: .quad szMessErrGC
qRed: .quad 0xFF0000
qGreen: .quad 0xFF00
qBlue: .quad 0xFF
qBlack: .quad 0x0
/******************************************************************/
/* create Graphic Context 1 */
/******************************************************************/
/* x0 contains the Display address */
/* x1 contains the ident Window */
createGC1:
stp x20,lr,[sp,-16]! // save registers
mov x20,x0 // save display address
mov x2,#0
mov x3,#0
bl XCreateGC
cbz x0,99f
mov x25,x0 // save GC
mov x0,x20 // display address
mov x1,x25
ldr x2,qBlanc // code RGB color
bl XSetForeground
cbz x0,99f
mov x0,x25 // return GC1
b 100f
99:
ldr x0,qAdrszMessErrGC
bl affichageMess
mov x0,0
100:
ldp x20,lr,[sp],16 // restaur 2 registers
ret // return to address lr x30
/******************************************************************/
/* create button on screen */
/******************************************************************/
createButton:
stp x21,lr,[sp,-16]! // save registers
// create button window
mov x0,x28 // display address
mov x1,x27 // ident window
mov x2,80 // X position
mov x3,150 // Y position
mov x4,60 // weight
mov x5,30 // height
mov x6,2 // border
ldr x7,qBlack
ldr x8,qBlanc // background
str x8,[sp,-16]! // argument fot stack
bl XCreateSimpleWindow
add sp,sp,16 // for stack alignement
cmp x0,#0 // error ?
beq 99f
ldr x21,qAdrstButton
str x0,[x21,BT_adresse] // save ident button
str xzr,[x21,BT_cbdata] // for next use
// autorisation des saisies
mov x0,x28 // display address
ldr x1,[x21,BT_adresse] // button address
ldr x2,qButtonMask // mask
bl XSelectInput
// create Graphic Contexte of button
mov x0,x28 // display address
ldr x1,[x21,BT_adresse] // button ident
mov x2,#0
mov x3,#0
bl XCreateGC
cmp x0,#0
beq 98f
str x0,[x21,BT_GC] // store GC
// display button
mov x0,x28 // display address
ldr x1,[x21,BT_adresse] // button address
bl XMapWindow
ldr x5,qAdrszTextButton // text address
mov x6,0 // text size
1: // loop compute text size
ldrb w10,[x5,x6] // load text byte
cbz x10,2f // zero -> end
add x6,x6,1 // increment size
b 1b // and loop
2:
mov x0,x28 // display address
ldr x1,[x21,BT_adresse] // button address
ldr x2,[x21,BT_GC] // GC address
mov x3,#8 // position x
mov x4,#15 // position y
bl XDrawString
b 100f
98:
ldr x0,qAdrszMessErrButtonGC
bl affichageMess
b 100f
99:
ldr x0,qAdrszMessErrButton
bl affichageMess
100:
ldp x1,lr,[sp],16 // restaur 2 registers
ret // return to address lr x30
qAdrstButton: .quad stButton
qAdrszTextButton: .quad szTextButton
qAdrszMessErrButtonGC: .quad szMessErrButtonGC
qAdrszMessErrButton: .quad szMessErrButton
qButtonMask: .quad ButtonPressMask|ButtonReleaseMask|StructureNotifyMask|ExposureMask|LeaveWindowMask|EnterWindowMask
/******************************************************************/
/* display text on screen */
/******************************************************************/
/* x0 contains the address of text */
displayText:
stp x1,lr,[sp,-16]! // save registers
mov x5,x0 // text address
mov x6,0 // text size
1: // loop compute text size
ldrb w10,[x5,x6] // load text byte
cbz x10,2f // zero -> end
add x6,x6,1 // increment size
b 1b // and loop
2:
mov x0,x28 // display address
mov x1,x27 // ident window
mov x2,x26 // GC address
mov x3,#50 // position x
mov x4,#100 // position y
bl XDrawString
100:
ldp x1,lr,[sp],16 // restaur 2 registers
ret // return to address lr x30
/******************************************************************/
/* events clic mouse button */
/******************************************************************/
/* x0 contains the address of event */
evtButtonMouse:
stp x1,lr,[sp,-16]! // save registers
ldr x10,[x0,XBE_window] // windows of event
ldr x11,qAdrstButton // load button ident
ldr x12,[x11,BT_adresse]
cmp x10,x12 // equal ?
bne 100f // no
bl eraseText // yes erase the text
ldr x10,qAdrqCounterClic // load counter clic
ldr x0,[x10]
add x0,x0,1 // and increment
str x0,[x10]
ldr x1,qAdrsZoneConv // and decimal conversion
bl conversion10
ldr x0,qAdrszMessResult
ldr x1,qAdrsZoneConv
bl strInsertAtCharInc // and insert result at @ character
bl displayText // and display new text
100:
ldp x1,lr,[sp],16 // restaur 2 registers
ret // return to address lr x30
qAdrqCounterClic: .quad qCounterClic
qAdrsZoneConv: .quad sZoneConv
qAdrszMessResult: .quad szMessResult
/******************************************************************/
/* erase text */
/******************************************************************/
eraseText:
stp x1,lr,[sp,-16]! // save registers
mov x0,x28 // display address
mov x1,x27 // ident window
mov x2,x25 // GC1 address
mov x3,20 // position x
mov x4,70 // position y
mov x5,400
mov x6,50
bl XFillRectangle
100:
ldp x1,lr,[sp],16 // restaur 2 registers
ret // return to address lr x30
/********************************************************/
/* File Include fonctions */
/********************************************************/
/* for this file see task include a file in language AArch64 assembly */
.include "../includeARM64.inc"
|
http://rosettacode.org/wiki/Singly-linked_list/Traversal | Singly-linked list/Traversal | Traverse from the beginning of a singly-linked list to the end.
See also
Array
Associative array: Creation, Iteration
Collections
Compound data type
Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal
Linked list
Queue: Definition, Usage
Set
Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal
Stack
| #Erlang | Erlang | 1> lists:map( fun erlang:is_integer/1, [1,2,3,a,b,c] ).
[true,true,true,false,false,false]
4> lists:foldl( fun erlang:'+'/2, 0, [1,2,3] ).
6
|
http://rosettacode.org/wiki/Singly-linked_list/Traversal | Singly-linked list/Traversal | Traverse from the beginning of a singly-linked list to the end.
See also
Array
Associative array: Creation, Iteration
Collections
Compound data type
Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal
Linked list
Queue: Definition, Usage
Set
Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal
Stack
| #Factor | Factor | : list-each ( linked-list quot: ( data -- ) -- )
[ [ data>> ] dip call ]
[ [ next>> ] dip over [ list-each ] [ 2drop ] if ] 2bi ; inline recursive
SYMBOLS: A B C ;
A <linked-list>
[ C <linked-list> list-insert ] keep
[ B <linked-list> list-insert ] keep
[ . ] list-each |
http://rosettacode.org/wiki/Singly-linked_list/Element_insertion | Singly-linked list/Element insertion | Singly-Linked List (element)
singly-linked list
Using this method, insert an element C into a list comprised of elements A->B, following element A.
See also
Array
Associative array: Creation, Iteration
Collections
Compound data type
Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal
Linked list
Queue: Definition, Usage
Set
Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal
Stack
| #E | E | def insertAfter(head :LinkedList ? (!head.null()),
new :LinkedList ? (new.next().null())) {
new.setNext(head.next())
head.setNext(new)
}
def a := makeLink(1, empty)
def b := makeLink(2, empty)
def c := makeLink(3, empty)
insertAfter(a, b)
insertAfter(a, c)
var x := a
while (!x.null()) {
println(x.value())
x := x.next()
} |
http://rosettacode.org/wiki/Singly-linked_list/Element_insertion | Singly-linked list/Element insertion | Singly-Linked List (element)
singly-linked list
Using this method, insert an element C into a list comprised of elements A->B, following element A.
See also
Array
Associative array: Creation, Iteration
Collections
Compound data type
Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal
Linked list
Queue: Definition, Usage
Set
Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal
Stack
| #EchoLisp | EchoLisp |
(define (insert-after lst target item)
(when (null? lst) (error "cannot insert in" null))
(let [(sub-list (member target lst))]
(if sub-list (set-cdr! sub-list (cons item (cdr sub-list))) ; make chirurgy if found
(nconc lst item)))) ; else append item
(define L '(a b))
(insert-after L 'a 'c)
L → (a c b)
(insert-after L 'x 'y)
L → (a c b y)
|
http://rosettacode.org/wiki/Sleep | Sleep | Task
Write a program that does the following in this order:
Input an amount of time to sleep in whatever units are most natural for your language (milliseconds, seconds, ticks, etc.). This unit should be noted in comments or in a description.
Print "Sleeping..."
Sleep the main thread for the given amount of time.
Print "Awake!"
End.
Related task
Nautical bell
| #C.2B.2B | C++ | #include <iostream>
#include <thread>
#include <chrono>
int main()
{
unsigned long microseconds;
std::cin >> microseconds;
std::cout << "Sleeping..." << std::endl;
std::this_thread::sleep_for(std::chrono::microseconds(microseconds));
std::cout << "Awake!\n";
}
|
http://rosettacode.org/wiki/Sorting_algorithms/Bubble_sort | Sorting algorithms/Bubble sort |
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:
O(n logn) sorts
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
A bubble sort is generally considered to be the simplest sorting algorithm.
A bubble sort is also known as a sinking sort.
Because of its simplicity and ease of visualization, it is often taught in introductory computer science courses.
Because of its abysmal O(n2) performance, it is not used often for large (or even medium-sized) datasets.
The bubble sort works by passing sequentially over a list, comparing each value to the one immediately after it. If the first value is greater than the second, their positions are switched. Over a number of passes, at most equal to the number of elements in the list, all of the values drift into their correct positions (large values "bubble" rapidly toward the end, pushing others down around them).
Because each pass finds the maximum item and puts it at the end, the portion of the list to be sorted can be reduced at each pass.
A boolean variable is used to track whether any changes have been made in the current pass; when a pass completes without changing anything, the algorithm exits.
This can be expressed in pseudo-code as follows (assuming 1-based indexing):
repeat
if itemCount <= 1
return
hasChanged := false
decrement itemCount
repeat with index from 1 to itemCount
if (item at index) > (item at (index + 1))
swap (item at index) with (item at (index + 1))
hasChanged := true
until hasChanged = false
Task
Sort an array of elements using the bubble sort algorithm. The elements must have a total order and the index of the array can be of any discrete type. For languages where this is not possible, sort an array of integers.
References
The article on Wikipedia.
Dance interpretation.
| #TI-83_BASIC | TI-83 BASIC | :L1→L2
:1+dim(L2)→N
:For(D,1,dim(L2))
:N-1→N
:0→I
:For(C,1,dim(L2)-2)
:For(A,dim(L2)-N+1,dim(L2)-1)
:If L2(A)>L2(A+1)
:Then
:1→I
:L2(A)→B
:L2(A+1)→L2(A)
:B→L2(A+1)
:End
:End
:End
:If I=0
:Goto C
:End
:Lbl C
:If L2(1)>L2(2)
:Then
:L2(1)→B
:L2(2)→L2(1)
:B→L2(2)
:End
:DelVar A
:DelVar B
:DelVar C
:DelVar D
:DelVar N
:DelVar I
:Return
|
http://rosettacode.org/wiki/Singly-linked_list/Element_definition | Singly-linked list/Element definition | singly-linked list
See also
Array
Associative array: Creation, Iteration
Collections
Compound data type
Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal
Linked list
Queue: Definition, Usage
Set
Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal
Stack | #JavaScript | JavaScript | function LinkedList(value, next) {
this._value = value;
this._next = next;
}
LinkedList.prototype.value = function() {
if (arguments.length == 1)
this._value = arguments[0];
else
return this._value;
}
LinkedList.prototype.next = function() {
if (arguments.length == 1)
this._next = arguments[0];
else
return this._next;
}
// convenience function to assist the creation of linked lists.
function createLinkedListFromArray(ary) {
var head = new LinkedList(ary[0], null);
var prev = head;
for (var i = 1; i < ary.length; i++) {
var node = new LinkedList(ary[i], null);
prev.next(node);
prev = node;
}
return head;
}
var head = createLinkedListFromArray([10,20,30,40]); |
http://rosettacode.org/wiki/Simple_windowed_application | Simple windowed application | Task
Create a window that has:
a label that says "There have been no clicks yet"
a button that says "click me"
Upon clicking the button with the mouse, the label should change and show the number of times the button has been clicked.
| #Ada | Ada | with Gdk.Event; use Gdk.Event;
with Gtk.Button; use Gtk.Button;
with Gtk.Label; use Gtk.Label;
with Gtk.Window; use Gtk.Window;
with Gtk.Widget; use Gtk.Widget;
with Gtk.Table; use Gtk.Table;
with Gtk.Handlers;
with Gtk.Main;
procedure Simple_Windowed_Application is
Window : Gtk_Window;
Grid : Gtk_Table;
Button : Gtk_Button;
Label : Gtk_Label;
Count : Natural := 0;
package Handlers is new Gtk.Handlers.Callback (Gtk_Widget_Record);
package Return_Handlers is
new Gtk.Handlers.Return_Callback (Gtk_Widget_Record, Boolean);
function Delete_Event (Widget : access Gtk_Widget_Record'Class)
return Boolean is
begin
return False;
end Delete_Event;
procedure Destroy (Widget : access Gtk_Widget_Record'Class) is
begin
Gtk.Main.Main_Quit;
end Destroy;
procedure Clicked (Widget : access Gtk_Widget_Record'Class) is
begin
Count := Count + 1;
Set_Text (Label, "The button clicks:" & Natural'Image (Count));
end Clicked;
begin
Gtk.Main.Init;
Gtk.Window.Gtk_New (Window);
Gtk_New (Grid, 1, 2, False);
Add (Window, Grid);
Gtk_New (Label, "There have been no clicks yet");
Attach (Grid, Label, 0, 1, 0, 1);
Gtk_New (Button, "Click me");
Attach (Grid, Button, 0, 1, 1, 2);
Return_Handlers.Connect
( Window,
"delete_event",
Return_Handlers.To_Marshaller (Delete_Event'Access)
);
Handlers.Connect
( Window,
"destroy",
Handlers.To_Marshaller (Destroy'Access)
);
Handlers.Connect
( Button,
"clicked",
Handlers.To_Marshaller (Clicked'Access)
);
Show_All (Grid);
Show (Window);
Gtk.Main.Main;
end Simple_Windowed_Application; |
http://rosettacode.org/wiki/Singly-linked_list/Traversal | Singly-linked list/Traversal | Traverse from the beginning of a singly-linked list to the end.
See also
Array
Associative array: Creation, Iteration
Collections
Compound data type
Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal
Linked list
Queue: Definition, Usage
Set
Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal
Stack
| #Fantom | Fantom | // traverse the linked list
Node? current := a
while (current != null)
{
echo (current.value)
current = current.successor
} |
http://rosettacode.org/wiki/Singly-linked_list/Traversal | Singly-linked list/Traversal | Traverse from the beginning of a singly-linked list to the end.
See also
Array
Associative array: Creation, Iteration
Collections
Compound data type
Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal
Linked list
Queue: Definition, Usage
Set
Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal
Stack
| #Forth | Forth | : last ( list -- end )
begin dup @ while @ repeat ; |
http://rosettacode.org/wiki/Singly-linked_list/Element_insertion | Singly-linked list/Element insertion | Singly-Linked List (element)
singly-linked list
Using this method, insert an element C into a list comprised of elements A->B, following element A.
See also
Array
Associative array: Creation, Iteration
Collections
Compound data type
Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal
Linked list
Queue: Definition, Usage
Set
Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal
Stack
| #Elena | Elena | singleton linkHelper
{
insertAfter(Link prev, IntNumber i)
{
prev.Next := new Link(i, prev.Next)
}
} |
http://rosettacode.org/wiki/Singly-linked_list/Element_insertion | Singly-linked list/Element insertion | Singly-Linked List (element)
singly-linked list
Using this method, insert an element C into a list comprised of elements A->B, following element A.
See also
Array
Associative array: Creation, Iteration
Collections
Compound data type
Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal
Linked list
Queue: Definition, Usage
Set
Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal
Stack
| #Erlang | Erlang |
-module( singly_linked_list ).
-export( [append/2, foreach/2, free/1, insert/3, new/1, task/0] ).
append( New, Start ) -> Start ! {append, New}.
foreach( Fun, Start ) -> Start ! {foreach, Fun}.
free( Element ) -> Element ! {free}.
insert( New, After, Start ) -> Start ! {insert, New, After}.
new( Data ) -> erlang:spawn( fun() -> loop( Data, nonext ) end ).
task() ->
A = new( a ),
B = new( b ),
append( B, A ),
C = new( c ),
insert( C, A, A ),
foreach( fun(Data) -> io:fwrite("~p~n", [Data]) end, A ).
loop( Data, Next ) ->
My_pid = erlang:self(),
receive
{append, New} ->
New_next = loop_append( New, Next ),
loop( Data, New_next );
{foreach, Fun} ->
catch Fun( Data ),
loop_foreach( Fun, Next ),
loop( Data, Next );
{free} ->
ok;
{insert, New, My_pid} ->
append( Next, New ),
loop( Data, New );
{insert, New, After} ->
Next ! {insert, New, After},
loop( Data, Next )
end.
loop_append( New, nonext ) -> New;
loop_append( New, Next ) ->
Next ! {append, New},
Next.
loop_foreach( _Fun, nonext ) -> ok;
loop_foreach( Fun, Next ) -> Next ! {foreach, Fun}.
|
http://rosettacode.org/wiki/Sleep | Sleep | Task
Write a program that does the following in this order:
Input an amount of time to sleep in whatever units are most natural for your language (milliseconds, seconds, ticks, etc.). This unit should be noted in comments or in a description.
Print "Sleeping..."
Sleep the main thread for the given amount of time.
Print "Awake!"
End.
Related task
Nautical bell
| #Cach.C3.A9_ObjectScript | Caché ObjectScript |
SLEEP
; the HANG command can use fractional seconds; the Awake line will be slightly off due to processing time
read "How long to sleep in seconds?: ",sleep
write !,"Sleeping... time is "_$ztime($piece($ztimestamp,",",2,2),1,2)
hang +sleep ; use + to cast numeric, if non-numeric will hang 0
write !,"Awake! Time is "_$ztime($piece($ztimestamp,",",2,2),1,2)
quit
|
http://rosettacode.org/wiki/Sleep | Sleep | Task
Write a program that does the following in this order:
Input an amount of time to sleep in whatever units are most natural for your language (milliseconds, seconds, ticks, etc.). This unit should be noted in comments or in a description.
Print "Sleeping..."
Sleep the main thread for the given amount of time.
Print "Awake!"
End.
Related task
Nautical bell
| #Clojure | Clojure | (defn sleep [ms] ; time in milliseconds
(println "Sleeping...")
(Thread/sleep ms)
(println "Awake!"))
; call it
(sleep 1000) |
http://rosettacode.org/wiki/Sorting_algorithms/Bubble_sort | Sorting algorithms/Bubble sort |
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:
O(n logn) sorts
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
A bubble sort is generally considered to be the simplest sorting algorithm.
A bubble sort is also known as a sinking sort.
Because of its simplicity and ease of visualization, it is often taught in introductory computer science courses.
Because of its abysmal O(n2) performance, it is not used often for large (or even medium-sized) datasets.
The bubble sort works by passing sequentially over a list, comparing each value to the one immediately after it. If the first value is greater than the second, their positions are switched. Over a number of passes, at most equal to the number of elements in the list, all of the values drift into their correct positions (large values "bubble" rapidly toward the end, pushing others down around them).
Because each pass finds the maximum item and puts it at the end, the portion of the list to be sorted can be reduced at each pass.
A boolean variable is used to track whether any changes have been made in the current pass; when a pass completes without changing anything, the algorithm exits.
This can be expressed in pseudo-code as follows (assuming 1-based indexing):
repeat
if itemCount <= 1
return
hasChanged := false
decrement itemCount
repeat with index from 1 to itemCount
if (item at index) > (item at (index + 1))
swap (item at index) with (item at (index + 1))
hasChanged := true
until hasChanged = false
Task
Sort an array of elements using the bubble sort algorithm. The elements must have a total order and the index of the array can be of any discrete type. For languages where this is not possible, sort an array of integers.
References
The article on Wikipedia.
Dance interpretation.
| #Toka | Toka | #! A simple Bubble Sort function
value| array count changed |
[ ( address count -- )
to count to array
count 0
[ count 0
[ i array array.get i 1 + array array.get 2dup >
[ i array array.put i 1 + array array.put ]
[ 2drop ] ifTrueFalse
] countedLoop
count 1 - to count
] countedLoop
] is bsort
#! Code to display an array
[ ( array count -- )
0 swap [ dup i swap array.get . ] countedLoop drop cr
] is .array
#! Create a 10-cell array
10 cells is-array foo
#! Fill it with random values
20 1 foo array.put
50 2 foo array.put
650 3 foo array.put
120 4 foo array.put
110 5 foo array.put
101 6 foo array.put
1321 7 foo array.put
1310 8 foo array.put
987 9 foo array.put
10 10 foo array.put
#! Display the array, sort it, and display it again
foo 10 .array
foo 10 bsort
foo 10 .array |
http://rosettacode.org/wiki/Singly-linked_list/Element_definition | Singly-linked list/Element definition | singly-linked list
See also
Array
Associative array: Creation, Iteration
Collections
Compound data type
Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal
Linked list
Queue: Definition, Usage
Set
Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal
Stack | #jq | jq | {"item": $item, "next": $next}
|
http://rosettacode.org/wiki/Singly-linked_list/Element_definition | Singly-linked list/Element definition | singly-linked list
See also
Array
Associative array: Creation, Iteration
Collections
Compound data type
Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal
Linked list
Queue: Definition, Usage
Set
Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal
Stack | #Julia | Julia | abstract type AbstractNode{T} end
struct EmptyNode{T} <: AbstractNode{T} end
mutable struct Node{T} <: AbstractNode{T}
data::T
next::AbstractNode{T}
end
Node{T}(x) where T = Node{T}(x::T, EmptyNode{T}())
mutable struct LinkedList{T}
head::AbstractNode{T}
end
LinkedList{T}() where T = LinkedList{T}(EmptyNode{T}())
LinkedList() = LinkedList{Any}()
Base.isempty(ll::LinkedList) = ll.head isa EmptyNode
function lastnode(ll::LinkedList)
if isempty(ll) throw(BoundsError()) end
nd = ll.head
while !(nd.next isa EmptyNode)
nd = nd.next
end
return nd
end
function Base.push!(ll::LinkedList{T}, x::T) where T
nd = Node{T}(x)
if isempty(ll)
ll.head = nd
else
tail = lastnode(ll)
tail.next = nd
end
return ll
end
function Base.pop!(ll::LinkedList{T}) where T
if isempty(ll)
throw(ArgumentError("list must be non-empty"))
elseif ll.head.next isa EmptyNode
nd = ll.head
ll.head = EmptyNode{T}()
else
nx = ll.head
while !isa(nx.next.next, EmptyNode)
nx = nx.next
end
nd = nx.next
nx.next = EmptyNode{T}()
end
return nd.data
end
lst = LinkedList{Int}()
push!(lst, 1)
push!(lst, 2)
push!(lst, 3)
pop!(lst) # 3
pop!(lst) # 2
pop!(lst) # 1 |
http://rosettacode.org/wiki/Simple_windowed_application | Simple windowed application | Task
Create a window that has:
a label that says "There have been no clicks yet"
a button that says "click me"
Upon clicking the button with the mouse, the label should change and show the number of times the button has been clicked.
| #APL | APL | ∇ WindowedApplication
⍝ define a form with a label and a button
'Frm'⎕WC'Form' 'Clicks' (40 35) (10 15)
'Lbl'Frm.⎕WC'Label' 'There have been no clicks yet.' (10 10)
'Btn'Frm.⎕WC'Button' 'Click Me' (35 35) (25 25) ('Event' 'Select' 'Click')
⍝ callback function
Frm.Clicks←0
Frm.Click←{
Clicks+←1
p0←(1+Clicks=1)⊃'have' 'has'
p1←(1+Clicks=1)⊃'clicks' 'click'
Lbl.Value←'There ',p0,' been ',(⍕Clicks),' ',p1,'.'
}
∇ |
http://rosettacode.org/wiki/Singly-linked_list/Traversal | Singly-linked list/Traversal | Traverse from the beginning of a singly-linked list to the end.
See also
Array
Associative array: Creation, Iteration
Collections
Compound data type
Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal
Linked list
Queue: Definition, Usage
Set
Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal
Stack
| #Fortran | Fortran | subroutine traversal(list,proc)
type(node), target :: list
type(node), pointer :: current
interface
subroutine proc(node)
real, intent(in) :: node
end subroutine proc
end interface
current => list
do while ( associated(current) )
call proc(current%data)
current => current%next
end do
end subroutine traversal |
http://rosettacode.org/wiki/Singly-linked_list/Traversal | Singly-linked list/Traversal | Traverse from the beginning of a singly-linked list to the end.
See also
Array
Associative array: Creation, Iteration
Collections
Compound data type
Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal
Linked list
Queue: Definition, Usage
Set
Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal
Stack
| #FreeBASIC | FreeBASIC | #define NULL 0
function alloc_ll_int( n as integer ) as ll_int ptr
dim as ll_int ptr ret = allocate(sizeof(ll_int))
ret->n = n
ret->nxt = NULL
return ret
end function
sub traverse_ll_int( head as ll_int ptr )
dim as ll_int ptr curr = head
while curr <> NULL
print curr->n
curr = curr->nxt
wend
end sub
dim as ll_int ptr curr, head = alloc_ll_int( 0 ), node
dim as integer i
curr=head
for i = 1 to 50
'build a list to traverse. This is basically a traversal itself...
node = alloc_ll_int( i )
insert_ll_int( curr, node )
curr = curr->nxt
next i
traverse_ll_int( head ) |
http://rosettacode.org/wiki/Singly-linked_list/Element_insertion | Singly-linked list/Element insertion | Singly-Linked List (element)
singly-linked list
Using this method, insert an element C into a list comprised of elements A->B, following element A.
See also
Array
Associative array: Creation, Iteration
Collections
Compound data type
Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal
Linked list
Queue: Definition, Usage
Set
Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal
Stack
| #Factor | Factor | : list-append ( previous new -- )
[ swap next>> >>next drop ] [ >>next drop ] 2bi ;
SYMBOLS: A B C ;
A <linked-list>
[ C <linked-list> list-append ] keep
[ B <linked-list> list-append ] keep
. |
http://rosettacode.org/wiki/Singly-linked_list/Element_insertion | Singly-linked list/Element insertion | Singly-Linked List (element)
singly-linked list
Using this method, insert an element C into a list comprised of elements A->B, following element A.
See also
Array
Associative array: Creation, Iteration
Collections
Compound data type
Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal
Linked list
Queue: Definition, Usage
Set
Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal
Stack
| #Fantom | Fantom |
class Node
{
const Int value
Node? successor // can be null, for end of series
new make (Int value, Node? successor := null)
{
this.value = value
this.successor = successor
}
// insert method for this problem
public Void insert (Node newNode)
{
newNode.successor = this.successor
this.successor = newNode
}
}
// simple class to test putting 'c' between 'a' and 'b'
class Main
{
public static Void main ()
{
c := Node (2)
b := Node (3)
a := Node (1, b)
a.insert (c)
echo (a.value)
echo (a.successor.value)
echo (a.successor.successor.value)
}
}
|
http://rosettacode.org/wiki/Sleep | Sleep | Task
Write a program that does the following in this order:
Input an amount of time to sleep in whatever units are most natural for your language (milliseconds, seconds, ticks, etc.). This unit should be noted in comments or in a description.
Print "Sleeping..."
Sleep the main thread for the given amount of time.
Print "Awake!"
End.
Related task
Nautical bell
| #COBOL | COBOL | IDENTIFICATION DIVISION.
PROGRAM-ID. Sleep-In-Seconds.
DATA DIVISION.
WORKING-STORAGE SECTION.
01 Seconds-To-Sleep USAGE COMP-2.
PROCEDURE DIVISION.
ACCEPT Seconds-To-Sleep
DISPLAY "Sleeping..."
CALL "C$SLEEP" USING BY CONTENT Seconds-To-Sleep
DISPLAY "Awake!"
GOBACK
. |
http://rosettacode.org/wiki/Sorting_algorithms/Bubble_sort | Sorting algorithms/Bubble sort |
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:
O(n logn) sorts
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
A bubble sort is generally considered to be the simplest sorting algorithm.
A bubble sort is also known as a sinking sort.
Because of its simplicity and ease of visualization, it is often taught in introductory computer science courses.
Because of its abysmal O(n2) performance, it is not used often for large (or even medium-sized) datasets.
The bubble sort works by passing sequentially over a list, comparing each value to the one immediately after it. If the first value is greater than the second, their positions are switched. Over a number of passes, at most equal to the number of elements in the list, all of the values drift into their correct positions (large values "bubble" rapidly toward the end, pushing others down around them).
Because each pass finds the maximum item and puts it at the end, the portion of the list to be sorted can be reduced at each pass.
A boolean variable is used to track whether any changes have been made in the current pass; when a pass completes without changing anything, the algorithm exits.
This can be expressed in pseudo-code as follows (assuming 1-based indexing):
repeat
if itemCount <= 1
return
hasChanged := false
decrement itemCount
repeat with index from 1 to itemCount
if (item at index) > (item at (index + 1))
swap (item at index) with (item at (index + 1))
hasChanged := true
until hasChanged = false
Task
Sort an array of elements using the bubble sort algorithm. The elements must have a total order and the index of the array can be of any discrete type. For languages where this is not possible, sort an array of integers.
References
The article on Wikipedia.
Dance interpretation.
| #TorqueScript | TorqueScript | //Note that we're assuming that the list of numbers is separated by tabs.
function bubbleSort(%list)
{
%ct = getFieldCount(%list);
for(%i = 0; %i < %ct; %i++)
{
for(%k = 0; %k < (%ct - %i - 1); %k++)
{
if(getField(%list, %k) > getField(%list, %k+1))
{
%tmp = getField(%list, %k);
%list = setField(%list, %k, getField(%list, %k+1));
%list = setField(%list, %k+1, %tmp);
}
}
}
return %list;
} |
http://rosettacode.org/wiki/Singly-linked_list/Element_definition | Singly-linked list/Element definition | singly-linked list
See also
Array
Associative array: Creation, Iteration
Collections
Compound data type
Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal
Linked list
Queue: Definition, Usage
Set
Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal
Stack | #Kotlin | Kotlin | // version 1.1.2
class Node<T: Number>(var data: T, var next: Node<T>? = null) {
override fun toString(): String {
val sb = StringBuilder(this.data.toString())
var node = this.next
while (node != null) {
sb.append(" -> ", node.data.toString())
node = node.next
}
return sb.toString()
}
}
fun main(args: Array<String>) {
val n = Node(1, Node(2, Node(3)))
println(n)
} |
http://rosettacode.org/wiki/Singly-linked_list/Element_definition | Singly-linked list/Element definition | singly-linked list
See also
Array
Associative array: Creation, Iteration
Collections
Compound data type
Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal
Linked list
Queue: Definition, Usage
Set
Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal
Stack | #Logo | Logo | fput item list ; add item to the head of a list
first list ; get the data
butfirst list ; get the remainder
bf list ; contraction for "butfirst" |
http://rosettacode.org/wiki/Simple_windowed_application | Simple windowed application | Task
Create a window that has:
a label that says "There have been no clicks yet"
a button that says "click me"
Upon clicking the button with the mouse, the label should change and show the number of times the button has been clicked.
| #AppleScript | AppleScript |
set counter to 0
set dialogReply to display dialog ¬
"There have been no clicks yet" buttons {"Click Me", "Quit"} ¬
with title "Simple Window Application"
set theAnswer to button returned of the result
if theAnswer is "Quit" then quit
repeat
set counter to counter + 1
set dialogReply to display dialog counter buttons {"Click Me", "Quit"} ¬
with title "Simple Window Application"
set theAnswer to button returned of the result
if theAnswer is "Quit" then exit repeat
end repeat
|
http://rosettacode.org/wiki/Singly-linked_list/Traversal | Singly-linked list/Traversal | Traverse from the beginning of a singly-linked list to the end.
See also
Array
Associative array: Creation, Iteration
Collections
Compound data type
Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal
Linked list
Queue: Definition, Usage
Set
Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal
Stack
| #Go | Go | start := &Ele{"tacos", nil}
end := start.Append("burritos")
end = end.Append("fajitas")
end = end.Append("enchilatas")
for iter := start; iter != nil; iter = iter.Next {
fmt.Println(iter)
} |
http://rosettacode.org/wiki/Singly-linked_list/Traversal | Singly-linked list/Traversal | Traverse from the beginning of a singly-linked list to the end.
See also
Array
Associative array: Creation, Iteration
Collections
Compound data type
Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal
Linked list
Queue: Definition, Usage
Set
Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal
Stack
| #Haskell | Haskell | map (>5) [1..10] -- [False,False,False,False,False,True,True,True,True,True]
map (++ "s") ["Apple", "Orange", "Mango", "Pear"] -- ["Apples","Oranges","Mangos","Pears"]
foldr (+) 0 [1..10] -- prints 55
traverse :: [a] -> [a]
traverse list = map func list
where func a = -- ...do something with a |
http://rosettacode.org/wiki/Singly-linked_list/Element_insertion | Singly-linked list/Element insertion | Singly-Linked List (element)
singly-linked list
Using this method, insert an element C into a list comprised of elements A->B, following element A.
See also
Array
Associative array: Creation, Iteration
Collections
Compound data type
Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal
Linked list
Queue: Definition, Usage
Set
Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal
Stack
| #Forth | Forth | \ Create the list and some list elements
create A 0 , char A ,
create B 0 , char B ,
create C 0 , char C , |
http://rosettacode.org/wiki/Singly-linked_list/Element_insertion | Singly-linked list/Element insertion | Singly-Linked List (element)
singly-linked list
Using this method, insert an element C into a list comprised of elements A->B, following element A.
See also
Array
Associative array: Creation, Iteration
Collections
Compound data type
Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal
Linked list
Queue: Definition, Usage
Set
Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal
Stack
| #Fortran | Fortran | elemental subroutine addAfter(nodeBefore,value)
type (node), intent(inout) :: nodeBefore
real, intent(in) :: value
type (node), pointer :: newNode
allocate(newNode)
newNode%data = value
newNode%next => nodeBefore%next
nodeBefore%next => newNode
end subroutine addAfter |
http://rosettacode.org/wiki/Sleep | Sleep | Task
Write a program that does the following in this order:
Input an amount of time to sleep in whatever units are most natural for your language (milliseconds, seconds, ticks, etc.). This unit should be noted in comments or in a description.
Print "Sleeping..."
Sleep the main thread for the given amount of time.
Print "Awake!"
End.
Related task
Nautical bell
| #Common_Lisp | Common Lisp | (defun test-sleep ()
(let ((seconds (read)))
(format t "Sleeping...~%")
(sleep seconds)
(format t "Awake!~%")))
(test-sleep) |
http://rosettacode.org/wiki/Sleep | Sleep | Task
Write a program that does the following in this order:
Input an amount of time to sleep in whatever units are most natural for your language (milliseconds, seconds, ticks, etc.). This unit should be noted in comments or in a description.
Print "Sleeping..."
Sleep the main thread for the given amount of time.
Print "Awake!"
End.
Related task
Nautical bell
| #D | D | import std.stdio, core.thread;
void main() {
write("Enter a time to sleep (in seconds): ");
long secs;
readf(" %d", &secs);
writeln("Sleeping...");
Thread.sleep(dur!"seconds"(secs));
writeln("Awake!");
} |
http://rosettacode.org/wiki/Sorting_algorithms/Bubble_sort | Sorting algorithms/Bubble sort |
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:
O(n logn) sorts
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
A bubble sort is generally considered to be the simplest sorting algorithm.
A bubble sort is also known as a sinking sort.
Because of its simplicity and ease of visualization, it is often taught in introductory computer science courses.
Because of its abysmal O(n2) performance, it is not used often for large (or even medium-sized) datasets.
The bubble sort works by passing sequentially over a list, comparing each value to the one immediately after it. If the first value is greater than the second, their positions are switched. Over a number of passes, at most equal to the number of elements in the list, all of the values drift into their correct positions (large values "bubble" rapidly toward the end, pushing others down around them).
Because each pass finds the maximum item and puts it at the end, the portion of the list to be sorted can be reduced at each pass.
A boolean variable is used to track whether any changes have been made in the current pass; when a pass completes without changing anything, the algorithm exits.
This can be expressed in pseudo-code as follows (assuming 1-based indexing):
repeat
if itemCount <= 1
return
hasChanged := false
decrement itemCount
repeat with index from 1 to itemCount
if (item at index) > (item at (index + 1))
swap (item at index) with (item at (index + 1))
hasChanged := true
until hasChanged = false
Task
Sort an array of elements using the bubble sort algorithm. The elements must have a total order and the index of the array can be of any discrete type. For languages where this is not possible, sort an array of integers.
References
The article on Wikipedia.
Dance interpretation.
| #uBasic.2F4tH | uBasic/4tH | PRINT "Bubble sort:"
n = FUNC (_InitArray)
PROC _ShowArray (n)
PROC _Bubblesort (n)
PROC _ShowArray (n)
PRINT
END
_Bubblesort PARAM(1) ' Bubble sort
LOCAL (2)
DO
b@ = 0
FOR c@ = 1 TO a@-1
IF @(c@-1) > @(c@) THEN PROC _Swap (c@, c@-1) : b@ = c@
NEXT
a@ = b@
UNTIL b@ = 0
LOOP
RETURN
_Swap PARAM(2) ' Swap two array elements
PUSH @(a@)
@(a@) = @(b@)
@(b@) = POP()
RETURN
_InitArray ' Init example array
PUSH 4, 65, 2, -31, 0, 99, 2, 83, 782, 1
FOR i = 0 TO 9
@(i) = POP()
NEXT
RETURN (i)
_ShowArray PARAM (1) ' Show array subroutine
FOR i = 0 TO a@-1
PRINT @(i),
NEXT
PRINT
RETURN |
http://rosettacode.org/wiki/Singly-linked_list/Element_definition | Singly-linked list/Element definition | singly-linked list
See also
Array
Associative array: Creation, Iteration
Collections
Compound data type
Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal
Linked list
Queue: Definition, Usage
Set
Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal
Stack | #Mathematica.2FWolfram_Language | Mathematica/Wolfram Language | Append[{}, x]
-> {x} |
http://rosettacode.org/wiki/Singly-linked_list/Element_definition | Singly-linked list/Element definition | singly-linked list
See also
Array
Associative array: Creation, Iteration
Collections
Compound data type
Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal
Linked list
Queue: Definition, Usage
Set
Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal
Stack | #Modula-2 | Modula-2 | TYPE
Link = POINTER TO LinkRcd;
LinkRcd = RECORD
Next: Link;
Data: INTEGER
END; |
http://rosettacode.org/wiki/Singly-linked_list/Element_definition | Singly-linked list/Element definition | singly-linked list
See also
Array
Associative array: Creation, Iteration
Collections
Compound data type
Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal
Linked list
Queue: Definition, Usage
Set
Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal
Stack | #Modula-3 | Modula-3 | TYPE
Link = REF LinkRcd;
LinkRcd = RECORD
Next: Link;
Data: INTEGER
END; |
http://rosettacode.org/wiki/Simple_windowed_application | Simple windowed application | Task
Create a window that has:
a label that says "There have been no clicks yet"
a button that says "click me"
Upon clicking the button with the mouse, the label should change and show the number of times the button has been clicked.
| #AutoHotkey | AutoHotkey | ; Create simple windowed application
Gui, Add, Text, vTextCtl, There have been no clicks yet ; add a Text-Control
Gui, Add, Button, gButtonClick xm, click me ; add a Button-Control
Gui, Show, , Simple windowed application ; show the Window
Return ; end of the auto-execute section
ButtonClick: ; the subroutine executed each time the Button-Control is clicked
count++ ; increment the click-counting var
GuiControl, , TextCtl, %count% ; update the Text-Control with the click-counting var
Return ; end of the subroutine
GuiClose: ; the subroutine executed when the Window is closed
ExitApp ; exit this process
Return |
http://rosettacode.org/wiki/Singly-linked_list/Traversal | Singly-linked list/Traversal | Traverse from the beginning of a singly-linked list to the end.
See also
Array
Associative array: Creation, Iteration
Collections
Compound data type
Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal
Linked list
Queue: Definition, Usage
Set
Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal
Stack
| #Icon_and_Unicon | Icon and Unicon | procedure main ()
ns := Node(1, Node(2, Node (3)))
until /ns do { # repeat until ns is null
write (ns.value)
ns := ns.successor
}
end |
http://rosettacode.org/wiki/Singly-linked_list/Traversal | Singly-linked list/Traversal | Traverse from the beginning of a singly-linked list to the end.
See also
Array
Associative array: Creation, Iteration
Collections
Compound data type
Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal
Linked list
Queue: Definition, Usage
Set
Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal
Stack
| #J | J | foo"0 {:"1 list |
http://rosettacode.org/wiki/Singly-linked_list/Element_insertion | Singly-linked list/Element insertion | Singly-Linked List (element)
singly-linked list
Using this method, insert an element C into a list comprised of elements A->B, following element A.
See also
Array
Associative array: Creation, Iteration
Collections
Compound data type
Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal
Linked list
Queue: Definition, Usage
Set
Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal
Stack
| #FreeBASIC | FreeBASIC | sub insert_ll_int( anchor as ll_int ptr, ins as ll_int ptr)
ins->nxt = anchor->nxt
anchor->nxt = ins
end sub |
http://rosettacode.org/wiki/Singly-linked_list/Element_insertion | Singly-linked list/Element insertion | Singly-Linked List (element)
singly-linked list
Using this method, insert an element C into a list comprised of elements A->B, following element A.
See also
Array
Associative array: Creation, Iteration
Collections
Compound data type
Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal
Linked list
Queue: Definition, Usage
Set
Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal
Stack
| #Go | Go | package main
import "fmt"
type Ele struct {
Data interface{}
Next *Ele
}
func (e *Ele) insert(data interface{}) {
if e == nil {
panic("attept to modify nil")
}
e.Next = &Ele{data, e.Next}
}
func (e *Ele) printList() {
if e == nil {
fmt.Println(nil)
return
}
fmt.Printf("(%v", e.Data)
for {
e = e.Next
if e == nil {
fmt.Println(")")
return
}
fmt.Print(" ", e.Data)
}
}
func main() {
h := &Ele{"A", &Ele{"B", nil}}
h.printList()
h.insert("C")
h.printList()
} |
http://rosettacode.org/wiki/Sleep | Sleep | Task
Write a program that does the following in this order:
Input an amount of time to sleep in whatever units are most natural for your language (milliseconds, seconds, ticks, etc.). This unit should be noted in comments or in a description.
Print "Sleeping..."
Sleep the main thread for the given amount of time.
Print "Awake!"
End.
Related task
Nautical bell
| #DCL | DCL | $ amount_of_time = p1 ! hour[:[minute][:[second][.[hundredth]]]]
$ write sys$output "Sleeping..."
$ wait 'amount_of_time
$ write sys$output "Awake!" |
http://rosettacode.org/wiki/Sleep | Sleep | Task
Write a program that does the following in this order:
Input an amount of time to sleep in whatever units are most natural for your language (milliseconds, seconds, ticks, etc.). This unit should be noted in comments or in a description.
Print "Sleeping..."
Sleep the main thread for the given amount of time.
Print "Awake!"
End.
Related task
Nautical bell
| #DBL | DBL | ;
; Sleep for DBL version 4 by Dario B.
;
PROC
;------------------------------------------------------------------
XCALL FLAGS (0007000000,1) ;Suppress STOP message
OPEN(1,O,'TT:')
DISPLAY (1,"Sleeping...",10)
SLEEP 10 ;Sleep for 10 seconds
DISPLAY (1,"Awake!",10)
|
http://rosettacode.org/wiki/Sorting_algorithms/Bubble_sort | Sorting algorithms/Bubble sort |
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:
O(n logn) sorts
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
A bubble sort is generally considered to be the simplest sorting algorithm.
A bubble sort is also known as a sinking sort.
Because of its simplicity and ease of visualization, it is often taught in introductory computer science courses.
Because of its abysmal O(n2) performance, it is not used often for large (or even medium-sized) datasets.
The bubble sort works by passing sequentially over a list, comparing each value to the one immediately after it. If the first value is greater than the second, their positions are switched. Over a number of passes, at most equal to the number of elements in the list, all of the values drift into their correct positions (large values "bubble" rapidly toward the end, pushing others down around them).
Because each pass finds the maximum item and puts it at the end, the portion of the list to be sorted can be reduced at each pass.
A boolean variable is used to track whether any changes have been made in the current pass; when a pass completes without changing anything, the algorithm exits.
This can be expressed in pseudo-code as follows (assuming 1-based indexing):
repeat
if itemCount <= 1
return
hasChanged := false
decrement itemCount
repeat with index from 1 to itemCount
if (item at index) > (item at (index + 1))
swap (item at index) with (item at (index + 1))
hasChanged := true
until hasChanged = false
Task
Sort an array of elements using the bubble sort algorithm. The elements must have a total order and the index of the array can be of any discrete type. For languages where this is not possible, sort an array of integers.
References
The article on Wikipedia.
Dance interpretation.
| #Unicon | Unicon | rm -f _sortpass
reset() {
test -f _tosort || mv _sortpass _tosort
}
bpass() {
(read a; read b
test -n "$b" -a "$a" && (
test $a -gt $b && (reset; echo $b; (echo $a ; cat) | bpass ) || (echo $a; (echo $b ; cat) | bpass )
) || echo $a)
}
bubblesort() {
cat > _tosort
while test -f _tosort
do
cat _tosort | (rm _tosort;cat) |bpass > _sortpass
done
cat _sortpass
}
cat to.sort | bubblesort |
http://rosettacode.org/wiki/Singly-linked_list/Element_definition | Singly-linked list/Element definition | singly-linked list
See also
Array
Associative array: Creation, Iteration
Collections
Compound data type
Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal
Linked list
Queue: Definition, Usage
Set
Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal
Stack | #Nanoquery | Nanoquery | class link
declare data
declare next
end |
http://rosettacode.org/wiki/Singly-linked_list/Element_definition | Singly-linked list/Element definition | singly-linked list
See also
Array
Associative array: Creation, Iteration
Collections
Compound data type
Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal
Linked list
Queue: Definition, Usage
Set
Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal
Stack | #Nim | Nim | type
Node[T] = ref object
next: Node[T]
data: T
SinglyLinkedList[T] = object
head, tail: Node[T]
proc newNode[T](data: T): Node[T] =
Node[T](data: data)
proc append[T](list: var SinglyLinkedList[T]; node: Node[T]) =
if list.head.isNil:
list.head = node
list.tail = node
else:
list.tail.next = node
list.tail = node
proc append[T](list: var SinglyLinkedList[T]; data: T) =
list.append newNode(data)
proc prepend[T](list: var SinglyLinkedList[T]; node: Node[T]) =
if list.head.isNil:
list.head = node
list.tail = node
else:
node.next = list.head
list.head = node
proc prepend[T](list: var SinglyLinkedList[T]; data: T) =
list.prepend newNode(data)
proc `$`[T](list: SinglyLinkedList[T]): string =
var s: seq[T]
var n = list.head
while not n.isNil:
s.add n.data
n = n.next
result = s.join(" → ")
var list: SinglyLinkedList[int]
for i in 1..5: list.append(i)
for i in 6..10: list.prepend(i)
echo "List: ", list |
http://rosettacode.org/wiki/Singly-linked_list/Element_definition | Singly-linked list/Element definition | singly-linked list
See also
Array
Associative array: Creation, Iteration
Collections
Compound data type
Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal
Linked list
Queue: Definition, Usage
Set
Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal
Stack | #Objective-C | Objective-C | #import <Foundation/Foundation.h>
@interface RCListElement<T> : NSObject
{
RCListElement<T> *next;
T datum;
}
- (RCListElement<T> *)next;
- (T)datum;
- (RCListElement<T> *)setNext: (RCListElement<T> *)nx;
- (void)setDatum: (T)d;
@end
@implementation RCListElement
- (RCListElement *)next
{
return next;
}
- (id)datum
{
return datum;
}
- (RCListElement *)setNext: (RCListElement *)nx
{
RCListElement *p = next;
next = nx;
return p;
}
- (void)setDatum: (id)d
{
datum = d;
}
@end |
http://rosettacode.org/wiki/Simple_windowed_application | Simple windowed application | Task
Create a window that has:
a label that says "There have been no clicks yet"
a button that says "click me"
Upon clicking the button with the mouse, the label should change and show the number of times the button has been clicked.
| #AutoIt | AutoIt |
#include <ButtonConstants.au3>
#include <GUIConstantsEx.au3>
#include <StaticConstants.au3>
#include <WindowsConstants.au3>
#Region ### START Koda GUI section ###
Local $GUI = GUICreate("Clicks", 280, 50, (@DesktopWidth - 280) / 2, (@DesktopHeight - 50) / 2)
Local $lblClicks = GUICtrlCreateLabel("There have been no clicks yet", 0, 0, 278, 20, $SS_CENTER)
Local $btnClicks = GUICtrlCreateButton("CLICK ME", 104, 25, 75, 25)
GUISetState(@SW_SHOW)
#EndRegion ### END Koda GUI section ###
Local $counter = 0
While 1
$nMsg = GUIGetMsg()
Switch $nMsg
Case $GUI_EVENT_CLOSE
Exit
Case $btnClicks
$counter += 1
GUICtrlSetData($lblClicks, "Times clicked: " & $counter)
EndSwitch
WEnd
|
http://rosettacode.org/wiki/Singly-linked_list/Traversal | Singly-linked list/Traversal | Traverse from the beginning of a singly-linked list to the end.
See also
Array
Associative array: Creation, Iteration
Collections
Compound data type
Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal
Linked list
Queue: Definition, Usage
Set
Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal
Stack
| #Java | Java | LinkedList<Type> list = new LinkedList<Type>();
for(Type i: list){
//each element will be in variable "i"
System.out.println(i);
} |
http://rosettacode.org/wiki/Singly-linked_list/Traversal | Singly-linked list/Traversal | Traverse from the beginning of a singly-linked list to the end.
See also
Array
Associative array: Creation, Iteration
Collections
Compound data type
Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal
Linked list
Queue: Definition, Usage
Set
Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal
Stack
| #JavaScript | JavaScript | LinkedList.prototype.traverse = function(func) {
func(this);
if (this.next() != null)
this.next().traverse(func);
}
LinkedList.prototype.print = function() {
this.traverse( function(node) {print(node.value())} );
}
var head = createLinkedListFromArray([10,20,30,40]);
head.print(); |
http://rosettacode.org/wiki/Singly-linked_list/Element_insertion | Singly-linked list/Element insertion | Singly-Linked List (element)
singly-linked list
Using this method, insert an element C into a list comprised of elements A->B, following element A.
See also
Array
Associative array: Creation, Iteration
Collections
Compound data type
Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal
Linked list
Queue: Definition, Usage
Set
Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal
Stack
| #Groovy | Groovy | class NodeList {
private enum Flag { FRONT }
private ListNode head
void insert(value, insertionPoint=Flag.FRONT) {
if (insertionPoint == Flag.FRONT) {
head = new ListNode(payload: value, next: head)
} else {
def node = head
while (node.payload != insertionPoint) {
node = node.next
if (node == null) {
throw new IllegalArgumentException(
"Insertion point ${afterValue} not already contained in list")
}
}
node.next = new ListNode(payload:value, next:node.next)
}
}
String toString() { "${head}" }
} |
http://rosettacode.org/wiki/Singly-linked_list/Element_insertion | Singly-linked list/Element insertion | Singly-Linked List (element)
singly-linked list
Using this method, insert an element C into a list comprised of elements A->B, following element A.
See also
Array
Associative array: Creation, Iteration
Collections
Compound data type
Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal
Linked list
Queue: Definition, Usage
Set
Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal
Stack
| #Haskell | Haskell | insertAfter a b (c:cs) | a==c = a : b : cs
| otherwise = c : insertAfter a b cs
insertAfter _ _ [] = error "Can't insert" |
http://rosettacode.org/wiki/Sleep | Sleep | Task
Write a program that does the following in this order:
Input an amount of time to sleep in whatever units are most natural for your language (milliseconds, seconds, ticks, etc.). This unit should be noted in comments or in a description.
Print "Sleeping..."
Sleep the main thread for the given amount of time.
Print "Awake!"
End.
Related task
Nautical bell
| #Delphi | Delphi | program SleepOneSecond;
{$APPTYPE CONSOLE}
uses SysUtils;
var
lTimeToSleep: Integer;
begin
if ParamCount = 0 then
lTimeToSleep := 1000
else
lTimeToSleep := StrToInt(ParamStr(1));
WriteLn('Sleeping...');
Sleep(lTimeToSleep); // milliseconds
WriteLn('Awake!');
end. |
http://rosettacode.org/wiki/Sleep | Sleep | Task
Write a program that does the following in this order:
Input an amount of time to sleep in whatever units are most natural for your language (milliseconds, seconds, ticks, etc.). This unit should be noted in comments or in a description.
Print "Sleeping..."
Sleep the main thread for the given amount of time.
Print "Awake!"
End.
Related task
Nautical bell
| #Diego | Diego | begin_instuct(sleepTime);
ask_human()_first()_msg(Enter number of seconds to sleep: )_var(sleepSecs)_me();
set_decision(asynchronous)_me();
me_msg(Sleeping...);
me_sleep[sleepSecs]_unit(secs);
me_msg(Awake!);
reset_decision()_me();
end_instruct(sleepTime);
exec_instruct(sleepTime)_me();
|
http://rosettacode.org/wiki/Sorting_algorithms/Bubble_sort | Sorting algorithms/Bubble sort |
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:
O(n logn) sorts
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
A bubble sort is generally considered to be the simplest sorting algorithm.
A bubble sort is also known as a sinking sort.
Because of its simplicity and ease of visualization, it is often taught in introductory computer science courses.
Because of its abysmal O(n2) performance, it is not used often for large (or even medium-sized) datasets.
The bubble sort works by passing sequentially over a list, comparing each value to the one immediately after it. If the first value is greater than the second, their positions are switched. Over a number of passes, at most equal to the number of elements in the list, all of the values drift into their correct positions (large values "bubble" rapidly toward the end, pushing others down around them).
Because each pass finds the maximum item and puts it at the end, the portion of the list to be sorted can be reduced at each pass.
A boolean variable is used to track whether any changes have been made in the current pass; when a pass completes without changing anything, the algorithm exits.
This can be expressed in pseudo-code as follows (assuming 1-based indexing):
repeat
if itemCount <= 1
return
hasChanged := false
decrement itemCount
repeat with index from 1 to itemCount
if (item at index) > (item at (index + 1))
swap (item at index) with (item at (index + 1))
hasChanged := true
until hasChanged = false
Task
Sort an array of elements using the bubble sort algorithm. The elements must have a total order and the index of the array can be of any discrete type. For languages where this is not possible, sort an array of integers.
References
The article on Wikipedia.
Dance interpretation.
| #UnixPipes | UnixPipes | rm -f _sortpass
reset() {
test -f _tosort || mv _sortpass _tosort
}
bpass() {
(read a; read b
test -n "$b" -a "$a" && (
test $a -gt $b && (reset; echo $b; (echo $a ; cat) | bpass ) || (echo $a; (echo $b ; cat) | bpass )
) || echo $a)
}
bubblesort() {
cat > _tosort
while test -f _tosort
do
cat _tosort | (rm _tosort;cat) |bpass > _sortpass
done
cat _sortpass
}
cat to.sort | bubblesort |
http://rosettacode.org/wiki/Singly-linked_list/Element_definition | Singly-linked list/Element definition | singly-linked list
See also
Array
Associative array: Creation, Iteration
Collections
Compound data type
Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal
Linked list
Queue: Definition, Usage
Set
Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal
Stack | #OCaml | OCaml | type 'a list = Nil | Cons of 'a * 'a list |
http://rosettacode.org/wiki/Singly-linked_list/Element_definition | Singly-linked list/Element definition | singly-linked list
See also
Array
Associative array: Creation, Iteration
Collections
Compound data type
Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal
Linked list
Queue: Definition, Usage
Set
Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal
Stack | #Oforth | Oforth | Collection Class new: LinkedList(data, mutable next) |
http://rosettacode.org/wiki/Singly-linked_list/Element_definition | Singly-linked list/Element definition | singly-linked list
See also
Array
Associative array: Creation, Iteration
Collections
Compound data type
Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal
Linked list
Queue: Definition, Usage
Set
Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal
Stack | #ooRexx | ooRexx |
list = .linkedlist~new
index = list~insert("abc") -- insert a first item, keeping the index
list~insert("def") -- adds to the end
list~insert("123", .nil) -- adds to the begining
list~insert("456", index) -- inserts between "abc" and "def"
list~remove(index) -- removes "abc"
say "Manual list traversal"
index = list~first -- demonstrate traversal
loop while index \== .nil
say index~value
index = index~next
end
say
say "Do ... Over traversal"
do value over list
say value
end
-- the main list item, holding the anchor to the links.
::class linkedlist
::method init
expose anchor
-- create this as an empty list
anchor = .nil
-- return first link element
::method first
expose anchor
return anchor
-- return last link element
::method last
expose anchor
current = anchor
loop while current \= .nil
-- found the last one
if current~next == .nil then return current
current = current~next
end
-- empty
return .nil
-- insert a value into the list, using the convention
-- followed by the built-in list class. If the index item
-- is omitted, add to the end. If the index item is .nil,
-- add to the end. Otherwise, just chain to the provided link.
::method insert
expose anchor
use arg value
newLink = .link~new(value)
-- adding to the end
if arg() == 1 then do
if anchor == .nil then anchor = newLink
else self~last~insert(newLink)
end
else do
use arg ,index
if index == .nil then do
if anchor \== .nil then newLink~next = anchor
anchor = newLink
end
else index~insert(newLink)
end
-- the link item serves as an "index"
return newLink
-- remove a link from the chain
::method remove
expose anchor
use strict arg index
-- handle the edge case
if index == anchor then anchor = anchor~next
else do
-- no back link, so we need to scan
previous = self~findPrevious(index)
-- invalid index, don't return any item
if previous == .nil then return .nil
previous~next = index~next
end
-- belt-and-braces, remove the link and return the value
index~next = .nil
return index~value
-- private method to find a link predecessor
::method findPrevious private
expose anchor
use strict arg index
-- we're our own precessor if this first
if index == anchor then return self
current = anchor
loop while current \== .nil
if current~next == index then return current
current = current~next
end
-- not found
return .nil
-- helper method to allow DO ... OVER traversal
::method makearray
expose anchor
array = .array~new
current = anchor
loop while current \= .nil
array~append(current~value)
current = current~next
end
return array
::class link
::method init
expose value next
-- by default, initialize both data and next to empty.
use strict arg value = .nil, next = .nil
-- allow external access to value and next link
::attribute value
::attribute next
::method insert
expose next
use strict arg newNode
newNode~next = next
next = newNode
|
http://rosettacode.org/wiki/Simple_windowed_application | Simple windowed application | Task
Create a window that has:
a label that says "There have been no clicks yet"
a button that says "click me"
Upon clicking the button with the mouse, the label should change and show the number of times the button has been clicked.
| #B4J | B4J |
#Region Project Attributes
#MainFormWidth: 593
#MainFormHeight: 179
#End Region
Sub Process_Globals
Private fx As JFX
Private MainForm As Form
Private btnClickMe As Button
Private lblClickCounter As Label
Private nClicks As Int = 0
Private aPlurals() As Object = Array As Object(Array As String("has","click"),Array As String("have","clicks"))
End Sub
Sub AppStart (Form1 As Form, Args() As String)
MainForm = Form1
MainForm.RootPane.LoadLayout("Layout1") 'Load the layout file.
MainForm.Show
End Sub
Sub btnClickMe_Action
nClicks = nClicks + 1
Dim aPlural() As Object = aPlurals(IIF(nClicks=1,0,1))
lblClickCounter.Text = "There " & aPlural(0) & " been " & (nClicks) & " " & aPlural(1) & " so far."
End Sub
Sub IIF(test As Boolean, trueVal As Object, falseVal As Object) As Object
If test Then
Return trueVal
Else
Return falseVal
End If
End Sub |
http://rosettacode.org/wiki/Singly-linked_list/Traversal | Singly-linked list/Traversal | Traverse from the beginning of a singly-linked list to the end.
See also
Array
Associative array: Creation, Iteration
Collections
Compound data type
Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal
Linked list
Queue: Definition, Usage
Set
Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal
Stack
| #jq | jq |
# Produce a stream of the items in the input SLL.
def items:
while(.; .next) | .item;
def to_singly_linked_list(s):
reduce ([s]|reverse[]) as $item (null; {$item, next:.});
# If f evaluates to empty at any item, that item is removed;
# if f evaluates to more than one item, all are added separately.
def map_singly_linked_list(f): to_singly_linked_list( items | f ); |
http://rosettacode.org/wiki/Singly-linked_list/Traversal | Singly-linked list/Traversal | Traverse from the beginning of a singly-linked list to the end.
See also
Array
Associative array: Creation, Iteration
Collections
Compound data type
Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal
Linked list
Queue: Definition, Usage
Set
Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal
Stack
| #Julia | Julia | Base.start(ll::LinkedList) = ll.head
Base.done(ll::LinkedList{T}, st::AbstractNode{T}) where T = st isa EmptyNode
Base.next(ll::LinkedList{T}, st::AbstractNode{T}) where T = st.data, st.next
lst = LinkedList{Int}()
push!(lst, 1)
push!(lst, 2)
push!(lst, 3)
for n in lst
print(n, " ")
end |
http://rosettacode.org/wiki/Singly-linked_list/Element_insertion | Singly-linked list/Element insertion | Singly-Linked List (element)
singly-linked list
Using this method, insert an element C into a list comprised of elements A->B, following element A.
See also
Array
Associative array: Creation, Iteration
Collections
Compound data type
Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal
Linked list
Queue: Definition, Usage
Set
Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal
Stack
| #Icon_and_Unicon | Icon and Unicon |
record Node (value, successor)
procedure insert_node (node, newNode)
newNode.successor := node.successor
node.successor := newNode
end
|
http://rosettacode.org/wiki/Singly-linked_list/Element_insertion | Singly-linked list/Element insertion | Singly-Linked List (element)
singly-linked list
Using this method, insert an element C into a list comprised of elements A->B, following element A.
See also
Array
Associative array: Creation, Iteration
Collections
Compound data type
Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal
Linked list
Queue: Definition, Usage
Set
Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal
Stack
| #J | J | list=: 1 65,:_ 66
A=:0 NB. reference into list
B=:1 NB. reference into list
insertAfter=: monad define
'localListName localListNode localNewValue'=. y
localListValue=: ".localListName
localOldLinkRef=: <localListNode,0
localNewLinkRef=: #localListValue
localNewNode=: (localOldLinkRef { localListValue), localNewValue
(localListName)=: (localNewLinkRef localOldLinkRef} localListValue), localNewNode
) |
http://rosettacode.org/wiki/Sleep | Sleep | Task
Write a program that does the following in this order:
Input an amount of time to sleep in whatever units are most natural for your language (milliseconds, seconds, ticks, etc.). This unit should be noted in comments or in a description.
Print "Sleeping..."
Sleep the main thread for the given amount of time.
Print "Awake!"
End.
Related task
Nautical bell
| #DIBOL-11 | DIBOL-11 |
START ;Demonstrate the SLEEP function
RECORD SLEEPING
, A8, "Sleeping"
RECORD WAKING
, A6,"Awake"
PROC
XCALL FLAGS (0007000000,1) ;Suppress STOP message
OPEN(8,O,'TT:')
WRITES(8,SLEEPING)
SLEEP 30 ; Sleep for 30 seconds
WRITES(8,WAKING)
END
|
http://rosettacode.org/wiki/Sleep | Sleep | Task
Write a program that does the following in this order:
Input an amount of time to sleep in whatever units are most natural for your language (milliseconds, seconds, ticks, etc.). This unit should be noted in comments or in a description.
Print "Sleeping..."
Sleep the main thread for the given amount of time.
Print "Awake!"
End.
Related task
Nautical bell
| #E | E | def sleep(milliseconds :int, nextThing) {
stdout.println("Sleeping...")
timer.whenPast(timer.now() + milliseconds, fn {
stdout.println("Awake!")
nextThing()
})
} |
http://rosettacode.org/wiki/Sorting_algorithms/Bubble_sort | Sorting algorithms/Bubble sort |
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:
O(n logn) sorts
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
A bubble sort is generally considered to be the simplest sorting algorithm.
A bubble sort is also known as a sinking sort.
Because of its simplicity and ease of visualization, it is often taught in introductory computer science courses.
Because of its abysmal O(n2) performance, it is not used often for large (or even medium-sized) datasets.
The bubble sort works by passing sequentially over a list, comparing each value to the one immediately after it. If the first value is greater than the second, their positions are switched. Over a number of passes, at most equal to the number of elements in the list, all of the values drift into their correct positions (large values "bubble" rapidly toward the end, pushing others down around them).
Because each pass finds the maximum item and puts it at the end, the portion of the list to be sorted can be reduced at each pass.
A boolean variable is used to track whether any changes have been made in the current pass; when a pass completes without changing anything, the algorithm exits.
This can be expressed in pseudo-code as follows (assuming 1-based indexing):
repeat
if itemCount <= 1
return
hasChanged := false
decrement itemCount
repeat with index from 1 to itemCount
if (item at index) > (item at (index + 1))
swap (item at index) with (item at (index + 1))
hasChanged := true
until hasChanged = false
Task
Sort an array of elements using the bubble sort algorithm. The elements must have a total order and the index of the array can be of any discrete type. For languages where this is not possible, sort an array of integers.
References
The article on Wikipedia.
Dance interpretation.
| #Ursala | Ursala | #import nat
bubblesort "p" = @iNX ^=T ^llPrEZryPrzPlrPCXlQ/~& @l ~&aitB^?\~&a "p"?ahthPX/~&ahPfatPRC ~&ath2fahttPCPRC
#cast %nL
example = bubblesort(nleq) <362,212,449,270,677,247,567,532,140,315> |
http://rosettacode.org/wiki/Singly-linked_list/Element_definition | Singly-linked list/Element definition | singly-linked list
See also
Array
Associative array: Creation, Iteration
Collections
Compound data type
Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal
Linked list
Queue: Definition, Usage
Set
Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal
Stack | #Pascal | Pascal | type
PLink = ^TLink;
TLink = record
FNext: PLink;
FData: integer;
end; |
http://rosettacode.org/wiki/Singly-linked_list/Element_definition | Singly-linked list/Element definition | singly-linked list
See also
Array
Associative array: Creation, Iteration
Collections
Compound data type
Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal
Linked list
Queue: Definition, Usage
Set
Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal
Stack | #Perl | Perl | my %node = (
data => 'say what',
next => \%foo_node,
);
$node{next} = \%bar_node; # mutable |
http://rosettacode.org/wiki/Simple_windowed_application | Simple windowed application | Task
Create a window that has:
a label that says "There have been no clicks yet"
a button that says "click me"
Upon clicking the button with the mouse, the label should change and show the number of times the button has been clicked.
| #BaCon | BaCon | OPTION GUI TRUE
PRAGMA GUI gtk3
gui = GUIDEFINE(" \
{ type=WINDOW name=window callback=delete-event title=\"Rosetta Code\" width-request=300 } \
{ type=BOX name=box parent=window orientation=GTK_ORIENTATION_VERTICAL } \
{ type=LABEL name=label parent=box height-request=50 label=\"There have been no clicks yet\" } \
{ type=BUTTON name=button parent=box callback=clicked label=\"Click Me\" }")
WHILE TRUE
SELECT GUIEVENT$(gui)
CASE "window"
BREAK
CASE "button"
INCR clicked
CALL GUISET(gui, "label", "label", "Button clicks: " & STR$(clicked))
ENDSELECT
WEND |
http://rosettacode.org/wiki/Simple_windowed_application | Simple windowed application | Task
Create a window that has:
a label that says "There have been no clicks yet"
a button that says "click me"
Upon clicking the button with the mouse, the label should change and show the number of times the button has been clicked.
| #BBC_BASIC | BBC BASIC | INSTALL @lib$+"WINLIB2"
INSTALL @lib$+"WINLIB5"
window% = FN_newdialog("Rosetta Code", 100, 100, 120, 52, 8, 1000)
PROC_static(window%, "There have been no clicks yet", 100, 10, 10, 100, 14, 0)
PROC_pushbutton(window%, "Click me", FN_setproc(PROCclick), 40, 30, 40, 16, 0)
PROC_showdialog(window%)
REPEAT
WAIT 1
UNTIL !window% = 0
QUIT
DEF PROCclick
PRIVATE clicks%
clicks% += 1
SYS "SetDlgItemText", !window%, 100, "Number of clicks = " + STR$(clicks%)
ENDPROC |
http://rosettacode.org/wiki/Singly-linked_list/Traversal | Singly-linked list/Traversal | Traverse from the beginning of a singly-linked list to the end.
See also
Array
Associative array: Creation, Iteration
Collections
Compound data type
Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal
Linked list
Queue: Definition, Usage
Set
Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal
Stack
| #Kotlin | Kotlin | fun main(args: Array<String>) {
val list = IntRange(1, 50).toList()
// classic traversal:
for (i in list) { print("%4d ".format(i)); if (i % 10 == 0) println() }
// list iterator:
list.asReversed().forEach { print("%4d ".format(it)); if (it % 10 == 1) println() }
} |
http://rosettacode.org/wiki/Singly-linked_list/Traversal | Singly-linked list/Traversal | Traverse from the beginning of a singly-linked list to the end.
See also
Array
Associative array: Creation, Iteration
Collections
Compound data type
Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal
Linked list
Queue: Definition, Usage
Set
Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal
Stack
| #Limbo | Limbo | implement Command;
include "sys.m";
sys: Sys;
include "draw.m";
include "sh.m";
init(nil: ref Draw->Context, nil: list of string)
{
sys = load Sys Sys->PATH;
l := list of {1, 2, 3, 4, 5};
# the unary 'tl' operator gets the tail of a list
for (; l != nil; l = tl l)
sys->print("%d\n", hd l);
# the unary 'hd' operator gets the head of a list
} |
http://rosettacode.org/wiki/Singly-linked_list/Element_insertion | Singly-linked list/Element insertion | Singly-Linked List (element)
singly-linked list
Using this method, insert an element C into a list comprised of elements A->B, following element A.
See also
Array
Associative array: Creation, Iteration
Collections
Compound data type
Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal
Linked list
Queue: Definition, Usage
Set
Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal
Stack
| #Java | Java | void insertNode(Node<T> anchor_node, Node<T> new_node)
{
new_node.next = anchor_node.next;
anchor_node.next = new_node;
} |
http://rosettacode.org/wiki/Singly-linked_list/Element_insertion | Singly-linked list/Element insertion | Singly-Linked List (element)
singly-linked list
Using this method, insert an element C into a list comprised of elements A->B, following element A.
See also
Array
Associative array: Creation, Iteration
Collections
Compound data type
Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal
Linked list
Queue: Definition, Usage
Set
Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal
Stack
| #JavaScript | JavaScript | LinkedList.prototype.insertAfter = function(searchValue, nodeToInsert) {
if (this._value == searchValue) {
nodeToInsert.next(this.next());
this.next(nodeToInsert);
}
else if (this.next() == null)
throw new Error(0, "value '" + searchValue + "' not found in linked list.")
else
this.next().insertAfter(searchValue, nodeToInsert);
}
var list = createLinkedListFromArray(['A','B']);
list.insertAfter('A', new LinkedList('C', null)); |
http://rosettacode.org/wiki/Sleep | Sleep | Task
Write a program that does the following in this order:
Input an amount of time to sleep in whatever units are most natural for your language (milliseconds, seconds, ticks, etc.). This unit should be noted in comments or in a description.
Print "Sleeping..."
Sleep the main thread for the given amount of time.
Print "Awake!"
End.
Related task
Nautical bell
| #EGL | EGL | program Sleep type BasicProgram{}
// Syntax: sysLib.wait(time BIN(9,2) in)
function main()
SysLib.writeStdout("Sleeping!");
sysLib.wait(15); // waits for 15 seconds
SysLib.writeStdout("Awake!");
end
end |
http://rosettacode.org/wiki/Sleep | Sleep | Task
Write a program that does the following in this order:
Input an amount of time to sleep in whatever units are most natural for your language (milliseconds, seconds, ticks, etc.). This unit should be noted in comments or in a description.
Print "Sleeping..."
Sleep the main thread for the given amount of time.
Print "Awake!"
End.
Related task
Nautical bell
| #Eiffel | Eiffel | class
APPLICATION
inherit
EXECUTION_ENVIRONMENT
create
make
feature -- Initialization
make
-- Sleep for a given number of nanoseconds.
do
print ("Enter a number of nanoseconds: ")
io.read_integer_64
print ("Sleeping...%N")
sleep (io.last_integer_64)
print ("Awake!%N")
end
end |
http://rosettacode.org/wiki/Sorting_algorithms/Bubble_sort | Sorting algorithms/Bubble sort |
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:
O(n logn) sorts
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
A bubble sort is generally considered to be the simplest sorting algorithm.
A bubble sort is also known as a sinking sort.
Because of its simplicity and ease of visualization, it is often taught in introductory computer science courses.
Because of its abysmal O(n2) performance, it is not used often for large (or even medium-sized) datasets.
The bubble sort works by passing sequentially over a list, comparing each value to the one immediately after it. If the first value is greater than the second, their positions are switched. Over a number of passes, at most equal to the number of elements in the list, all of the values drift into their correct positions (large values "bubble" rapidly toward the end, pushing others down around them).
Because each pass finds the maximum item and puts it at the end, the portion of the list to be sorted can be reduced at each pass.
A boolean variable is used to track whether any changes have been made in the current pass; when a pass completes without changing anything, the algorithm exits.
This can be expressed in pseudo-code as follows (assuming 1-based indexing):
repeat
if itemCount <= 1
return
hasChanged := false
decrement itemCount
repeat with index from 1 to itemCount
if (item at index) > (item at (index + 1))
swap (item at index) with (item at (index + 1))
hasChanged := true
until hasChanged = false
Task
Sort an array of elements using the bubble sort algorithm. The elements must have a total order and the index of the array can be of any discrete type. For languages where this is not possible, sort an array of integers.
References
The article on Wikipedia.
Dance interpretation.
| #Vala | Vala | void swap(int[] array, int i1, int i2) {
if (array[i1] == array[i2])
return;
var tmp = array[i1];
array[i1] = array[i2];
array[i2] = tmp;
}
void bubble_sort(int[] array) {
bool flag = true;
int j = array.length;
while(flag) {
flag = false;
for (int i = 1; i < j; i++) {
if (array[i] < array[i - 1]) {
swap(array, i - 1, i);
flag = true;
}
}
j--;
}
}
void main() {
int[] array = {5, -1, 101, -4, 0, 1, 8, 6, 2, 3};
bubble_sort(array);
foreach (int i in array)
print("%d ", i);
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.