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_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 | #Phix | Phix | enum NEXT,DATA
type slnode(object x)
return (sequence(x) and length(x)=DATA and myotherudt(x[DATA]) and integer(x[NEXT])
end type
|
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 | #PicoLisp | PicoLisp |
declare 1 node based (p),
2 value fixed,
2 link pointer;
|
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.
| #Beads | Beads | beads 1 program simple title:'Simple windowed application' // written by CodingFiend
var g : record // global tracked mutable state
label : str
nclicks : num
========================
calc main_init // our one time initialization for the program
g.label = "There have been no clicks yet"
g.nclicks = 0
========================
// In beads you subdivide the screen by slicing it horizontally or vertically
// so as to gradually break it down into pieces, some of which are drawn
horz slice main_draw // our main drawing function
under
draw_rect(fill:DARK_SLATE_GRAY) // fill entire screen
// slice the screen into 3 horz pieces, leaving 200 pt for our body
skip 10 al
add 200 pt main_draw2
skip 10 al
vert slice main_draw2 // now take the middle horz slice, and slice it vertically
skip 10 al
add 50 pt draw_click_count
skip 2 al
add 80 px draw_button
skip 10 al
========================
draw draw_click_count
draw_str(g.label, size:0.7, color:WHITE)
========================
draw draw_button
draw_rect(fill:ORANGE, corner:20 pt, thick:2 pt, color:BROWN)
draw_str("Click me", size:40, indent:8 pt, color:BLACK)
-------------------
track EV_TAP
// update our click count
inc g.nclicks
g.label = to_str(g.nclicks) |
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
| #Logo | Logo | to last :list
if empty? bf :list [output first :list]
output last bf :list
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
| #Logtalk | Logtalk |
:- object(singly_linked_list).
:- public(show/0).
show :-
traverse([1,2,3]).
traverse([]).
traverse([Head| Tail]) :-
write(Head), nl,
traverse(Tail).
:- end_object.
|
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
| #jq | jq | def new($item; $next):
if $next | (.==null or is_singly_linked_list)
then {$item, $next}
else "new(_;_) called with invalid SLL: \($next)" | error
end;
# A constructor:
def new($x): new($x; null);
def insert($x):
.next |= new($x; .); |
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
| #Julia | Julia | function Base.insert!(ll::LinkedList{T}, index::Integer, item::T) where T
if index == 1
if isempty(ll)
return push!(ll, item)
else
ll.head = Node{T}(item, ll.head)
end
else
nd = ll.head
while index > 2
if nd.next isa EmptyNode
throw(BoundsError())
else
nd = nd.next
index -= 1
end
end
nd.next = Node{T}(item, nd.next)
end
return ll
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
| #Elena | Elena | import extensions;
public program()
{
int sleep := console.readLine().toInt();
console.printLine("Sleeping...");
system'threading'threadControl.sleep(sleep);
console.printLine("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
| #Elixir | Elixir | sleep = fn seconds ->
IO.puts "Sleeping..."
:timer.sleep(1000 * seconds) # in milliseconds
IO.puts "Awake!"
end
sec = if System.argv==[], do: 1, else: hd(System.argv) |> String.to_integer
sleep.(sec) |
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.
| #VBA | VBA | Private Function bubble_sort(s As Variant) As Variant
Dim tmp As Variant
Dim changed As Boolean
For j = UBound(s) To 1 Step -1
changed = False
For i = 1 To j - 1
If s(i) > s(i + 1) Then
tmp = s(i)
s(i) = s(i + 1)
s(i + 1) = tmp
changed = True
End If
Next i
If Not changed Then
Exit For
End If
Next j
bubble_sort = s
End Function
Public Sub main()
s = [{4, 15, "delta", 2, -31, 0, "alfa", 19, "gamma", 2, 13, "beta", 782, 1}]
Debug.Print "Before: "
Debug.Print Join(s, ", ")
Debug.Print "After: "
Debug.Print Join(bubble_sort(s), ", ")
End Sub |
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 | #PL.2FI | PL/I |
declare 1 node based (p),
2 value fixed,
2 link pointer;
|
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 | #Pop11 | Pop11 | ;;; Use shorthand syntax to create list.
lvars l1 = [1 2 three 'four'];
;;; Allocate a single list node, with value field 1 and the link field
;;; pointing to empty list
lvars l2 = cons(1, []);
;;; print first element of l1
front(l1) =>
;;; print the rest of l1
back(l1) =>
;;; Use index notation to access third element
l1(3) =>
;;; modify link field of l2 to point to l1
l1 -> back(l2);
;;; Print l2
l2 => |
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 | #PureBasic | PureBasic | Structure MyData
*next.MyData
Value.i
EndStructure |
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.
| #C | C | #include <stdio.h>
#include <gtk/gtk.h>
const gchar *clickme = "Click Me";
guint counter = 0;
#define MAXLEN 64
void clickedme(GtkButton *o, gpointer d)
{
GtkLabel *l = GTK_LABEL(d);
char nt[MAXLEN];
counter++;
snprintf(nt, MAXLEN, "You clicked me %d times", counter);
gtk_label_set_text(l, nt);
}
int main(int argc, char **argv)
{
GtkWindow *win;
GtkButton *button;
GtkLabel *label;
GtkVBox *vbox;
gtk_init(&argc, &argv);
win = (GtkWindow*)gtk_window_new(GTK_WINDOW_TOPLEVEL);
gtk_window_set_title(win, clickme);
button = (GtkButton*)gtk_button_new_with_label(clickme);
label = (GtkLabel*)gtk_label_new("There have been no clicks yet");
gtk_label_set_single_line_mode(label, TRUE);
vbox = (GtkVBox*)gtk_vbox_new(TRUE, 1);
gtk_container_add(GTK_CONTAINER(vbox), GTK_WIDGET(label));
gtk_container_add(GTK_CONTAINER(vbox), GTK_WIDGET(button));
gtk_container_add(GTK_CONTAINER(win), GTK_WIDGET(vbox));
g_signal_connect(G_OBJECT(win), "delete-event", (GCallback)gtk_main_quit, NULL);
g_signal_connect(G_OBJECT(button), "clicked", (GCallback)clickedme, label);
gtk_widget_show_all(GTK_WIDGET(win));
gtk_main();
return 0;
} |
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
| #Mathematica.2FWolfram_Language | Mathematica/Wolfram Language | Print /@ {"rosettacode", "kitten", "sitting", "rosettacode", "raisethysword"} |
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
| #MATLAB_.2F_Octave | MATLAB / Octave | list = 1:10;
for k=1:length(list)
printf('%i\n',list(k))
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
| #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 <T: Number> insertAfter(prev: Node<T>, new: Node<T>) {
new.next = prev.next
prev.next = new
}
fun main(args: Array<String>) {
val b = Node(3)
val a = Node(1, b)
println("Before insertion : $a")
val c = Node(2)
insertAfter(a, c)
println("After insertion : $a")
} |
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
| #Emacs_Lisp | Emacs Lisp | (let ((seconds (read-number "Time in seconds: ")))
(message "Sleeping ...")
(sleep-for seconds)
(message "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.
| #VBScript | VBScript |
sub decr( byref n )
n = n - 1
end sub
sub incr( byref n )
n = n + 1
end sub
sub swap( byref a, byref b)
dim tmp
tmp = a
a = b
b = tmp
end sub
function bubbleSort( a )
dim changed
dim itemCount
itemCount = ubound(a)
do
changed = false
decr itemCount
for i = 0 to itemCount
if a(i) > a(i+1) then
swap a(i), a(i+1)
changed = true
end if
next
loop until not changed
bubbleSort = a
end function
|
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 | #Python | Python | class LinkedList(object):
"""USELESS academic/classroom example of a linked list implemented in Python.
Don't ever consider using something this crude! Use the built-in list() type!
"""
class Node(object):
def __init__(self, item):
self.value = item
self.next = None
def __init__(self, item=None):
if item is not None:
self.head = Node(item); self.tail = self.head
else:
self.head = None; self.tail = None
def append(self, item):
if not self.head:
self.head = Node(item)
self.tail = self.head
elif self.tail:
self.tail.next = Node(item)
self.tail = self.tail.next
else:
self.tail = Node(item)
def __iter__(self):
cursor = self.head
while cursor:
yield cursor.value
cursor = cursor.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 | #Racket | Racket |
#lang racket
(mcons 1 (mcons 2 (mcons 3 '()))) ; a mutable list
|
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.
| #C.23 | C# | using System.Windows.Forms;
class RosettaForm : Form
{
RosettaForm()
{
var clickCount = 0;
var label = new Label();
label.Text = "There have been no clicks yet.";
label.Dock = DockStyle.Top;
Controls.Add(label);
var button = new Button();
button.Text = "Click Me";
button.Dock = DockStyle.Bottom;
button.Click += delegate
{
clickCount++;
label.Text = "Number of clicks: " + clickCount + ".";
};
Controls.Add(button);
}
static void Main()
{
Application.Run(new RosettaForm());
}
}
|
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
| #MiniScript | MiniScript | myList = [2, 4, 6, 8]
for i in myList
print i
end for |
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
| #Nanoquery | Nanoquery | first = new(link)
//
for (iter = first) (iter != null) (iter = iter.next)
println iter.data
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
| #Logo | Logo | to insert :after :list :value
localmake "tail member :after :list
if not empty? :tail [.setbf :tail fput :value bf :tail]
output :list
end
show insert 5 [3 5 1 8] 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
| #Mathematica.2FWolfram_Language | Mathematica/Wolfram Language | Append[{a, b}, c]
->{a, b, c} |
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
| #Erlang | Erlang | main() ->
io:format("Sleeping...~n"),
timer:sleep(1000), %% in milliseconds
io:format("Awake!~n"). |
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
| #ERRE | ERRE |
..............
INPUT("Enter the time to sleep in seconds: ";sleep)
PRINT("Sleeping...")
PAUSE(sleep)
PRINT("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.
| #Visual_Basic_.NET | Visual Basic .NET | Do Until NoMoreSwaps = True
NoMoreSwaps = True
For Counter = 1 To (NumberOfItems - 1)
If List(Counter) > List(Counter + 1) Then
NoMoreSwaps = False
Temp = List(Counter)
List(Counter) = List(Counter + 1)
List(Counter + 1) = Temp
End If
Next
NumberOfItems = NumberOfItems - 1
Loop |
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 | #Raku | Raku | my $elem = 42 => $nextelem; |
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 | #REXX | REXX | /*REXX program demonstrates how to create and show a single-linked list.*/
@.=0 /*define a null linked list. */
call set@ 3 /*linked list: 12 Proth Primes. */
call set@ 5
call set@ 13
call set@ 17
call set@ 41
call set@ 97
call set@ 113
call set@ 193
call set@ 241
call set@ 257
call set@ 353
call set@ 449
[email protected]_width /*use the maximum width of nums. */
call list@ /*list all the elements in list. */
exit /*stick a fork in it, we're done.*/
/*──────────────────────────────────LIST@ subroutine────────────────────*/
list@: say; w=max(7, @.max_width ) /*use the max width of nums or 7.*/
say center('item',6) center('value',w) center('next',6)
say center('' ,6,'─') center('' ,w,'─') center('' ,6,'─')
p=1
do j=1 until p==0 /*show all entries of linked list*/
say right(j,6) right(@.p._value,w) right(@.p._next,6)
[email protected]._next
end /*j*/
return
/*──────────────────────────────────SET@ subroutine─────────────────────*/
set@: procedure expose @.; parse arg y /*get element to be added to list*/
_=@._last /*set the previous last element. */
n=_+1 /*bump last ptr in linked list. */
@._._next=n /*set the next pointer value. */
@._last=n /*define next item in linked list*/
@.n._value=y /*set item to the value specified*/
@.n._next=0 /*set the next pointer value. */
@..y=n /*set a locator pointer to self. */
@.max_width=max(@.max_width,length(y)) /*set maximum width of any value.*/
return /*return to invoker of this sub. */ |
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.
| #C.2B.2B | C++ | #ifndef CLICKCOUNTER_H
#define CLICKCOUNTER_H
#include <QWidget>
class QLabel ;
class QPushButton ;
class QVBoxLayout ;
class Counter : public QWidget {
Q_OBJECT
public :
Counter( QWidget * parent = 0 ) ;
private :
int number ;
QLabel *countLabel ;
QPushButton *clicker ;
QVBoxLayout *myLayout ;
private slots :
void countClicks( ) ;
} ;
#endif |
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
| #NewLISP | NewLISP | (dolist (x '(a b c d e))
(println x)) |
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
| #Nim | Nim | type Node[T] = ref object
next: Node[T]
data: T
proc newNode[T](data: T): Node[T] =
Node[T](data: data)
var a = newNode 12
var b = newNode 13
var c = newNode 14
proc insertAppend(a, n: var Node) =
n.next = a.next
a.next = n
a.insertAppend(b)
b.insertAppend(c)
iterator items(a: Node) =
var x = a
while not x.isNil:
yield x
x = x.next
for item in a:
echo item.data |
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
| #Modula-3 | Modula-3 | MODULE SinglyLinkedList EXPORTS Main;
TYPE
Link = REF LinkRcd;
LinkRcd = RECORD
Next: Link;
Data: INTEGER
END;
PROCEDURE InsertAppend(anchor, next: Link) =
BEGIN
IF anchor # NIL AND next # NIL THEN
next.Next := anchor.Next;
anchor.Next := next
END
END InsertAppend;
VAR
a: Link := NEW(Link, Next := NIL, Data := 1);
b: Link := NEW(Link, Next := NIL, Data := 2);
c: Link := NEW(Link, Next := NIL, Data := 3);
BEGIN
InsertAppend(a, b);
InsertAppend(a, c)
END SinglyLinkedList. |
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
| #Nim | Nim | type Node[T] = ref object
next: Node[T]
data: T
proc newNode[T](data: T): Node[T] =
Node[T](data: data)
var a = newNode 12
var b = newNode 13
var c = newNode 14
proc insertAppend(a, n: var Node) =
n.next = a.next
a.next = n
a.insertAppend(b)
b.insertAppend(c) |
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
| #F.23 | F# | open System
open System.Threading
[<EntryPoint>]
let main args =
let sleep = Convert.ToInt32(Console.ReadLine())
Console.WriteLine("Sleeping...")
Thread.Sleep(sleep); //milliseconds
Console.WriteLine("Awake!")
0 |
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
| #Factor | Factor | USING: calendar io math.parser threads ;
: read-sleep ( -- )
readln string>number seconds
"Sleeping..." print
sleep
"Awake!" print ; |
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.
| #Vlang | Vlang | fn bubble(mut arr []int) {
println('Input: ${arr.str()}')
mut count := arr.len
for {
if count <= 1 {
break
}
mut has_changed := false
count--
for i := 0; i < count; i++ {
if arr[i] > arr[i + 1] {
temp := arr[i + 1]
arr[i + 1] = arr[i]
arr[i] = temp
has_changed = true
}
}
if !has_changed {
break
}
}
println('Output: ${arr.str()}')
}
fn main() {
mut arr := [3, 5, 2, 1, 4]
bubble(mut arr)
} |
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 | #Ruby | Ruby | class ListNode
attr_accessor :value, :succ
def initialize(value, succ=nil)
self.value = value
self.succ = succ
end
def each(&b)
yield self
succ.each(&b) if succ
end
include Enumerable
def self.from_array(ary)
head = self.new(ary[0], nil)
prev = head
ary[1..-1].each do |val|
node = self.new(val, nil)
prev.succ = node
prev = node
end
head
end
end
list = ListNode.from_array([1,2,3,4]) |
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 | #Run_BASIC | Run BASIC | data = 10
link = 10
dim node{data,link} |
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.
| #Clojure | Clojure | (ns counter-window
(:import (javax.swing JFrame JLabel JButton)))
(defmacro on-action [component event & body]
`(. ~component addActionListener
(proxy [java.awt.event.ActionListener] []
(actionPerformed [~event] ~@body))))
(defn counter-app []
(let [counter (atom 0)
label (JLabel. "There have been no clicks yet")
button (doto (JButton. "Click me!")
(on-action evnt
(.setText label
(str "Counter: " (swap! counter inc)))))
panel (doto (JPanel.)
(.setOpaque true)
(.add label)
(.add button))]
(doto (JFrame. "Counter App")
(.setContentPane panel)
(.setSize 300 100)
(.setDefaultCloseOperation JFrame/EXIT_ON_CLOSE)
(.setVisible true))))
|
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
| #Objeck | Objeck |
for(node := head; node <> Nil; node := node->GetNext();) {
node->GetValue()->PrintLine();
};
|
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
| #Objective-C | Objective-C | RCListElement *current;
for(current=first_of_the_list; current != nil; current = [current next] )
{
// to get the "datum":
// id dat_obj = [current datum];
} |
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
| #OCaml | OCaml | let rec insert_after a b = function
c :: cs when a = c -> a :: b :: cs
| c :: cs -> c :: insert_after a b cs
| [] -> raise Not_found |
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
| #Oforth | Oforth | Collection Class new: LinkedList(data, mutable next)
LinkedList method: initialize := next := data ;
LinkedList method: data @data ;
LinkedList method: next @next ;
LinkedList method: add(e) e @next LinkedList new := next ;
LinkedList method: forEachNext
dup ifNull: [ drop self ]
dup 1 ifEq: [ drop false return ]
dup next dup ifNull: [ drop 1 ]
swap data true ;
: testLink LinkedList new($A, null) dup add($B) dup add($C) ;
testLink println |
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
| #Fantom | Fantom |
using concurrent
class Main
{
public static Void main ()
{
echo ("Enter a time to sleep: ")
input := Env.cur.in.readLine
try
{
time := Duration.fromStr (input)
echo ("sleeping ...")
Actor.sleep (time)
echo ("awake!")
}
catch
{
echo ("Invalid time entered")
}
}
}
|
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
| #FBSL | FBSL | #APPTYPE CONSOLE
DIM %msec
PRINT "Milliseconds to sleep: ";
%msec = FILEGETS(stdin, 10)
PRINT "Sleeping..."
SLEEP(%msec)
PRINT "Awake!"
PAUSE
|
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.
| #Wren | Wren | var bubbleSort = Fn.new { |a|
var n = a.count
if (n < 2) return
while (true) {
var swapped = false
for (i in 1..n-1) {
if (a[i-1] > a[i]) {
var t = a[i-1]
a[i-1] = a[i]
a[i] = t
swapped = true
}
}
if (!swapped) return
}
}
var as = [ [4, 65, 2, -31, 0, 99, 2, 83, 782, 1], [7, 5, 2, 6, 1, 4, 2, 6, 3] ]
for (a in as) {
System.print("Before: %(a)")
bubbleSort.call(a)
System.print("After : %(a)")
System.print()
} |
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 | #Rust | Rust | struct Node<T> {
elem: T,
next: Option<Box<Node<T>>>,
} |
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 | #Scala | Scala |
sealed trait List[+A]
case class Cons[+A](head: A, tail: List[A]) extends List[A]
case object Nil extends List[Nothing]
object List {
def apply[A](as: A*): List[A] =
if (as.isEmpty) Nil else Cons(as.head, apply(as.tail: _*))
}
|
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.
| #Common_Lisp | Common Lisp | (defpackage #:rcswa
(:use #:clim #:clim-lisp))
(in-package #:rcswa) |
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
| #OCaml | OCaml | # let li = ["big"; "fjords"; "vex"; "quick"; "waltz"; "nymph"] in
List.iter print_endline li ;;
big
fjords
vex
quick
waltz
nymph
- : unit = () |
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
| #Oforth | Oforth | : testLink LinkedList new($A, null) dup add($B) dup add($C) ;
testLink apply(#println) |
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
| #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"
|
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
| #Pascal | Pascal | type
pCharNode = ^CharNode;
CharNode = record
data: char;
next: pCharNode;
end;
(* This procedure inserts a node (newnode) directly after another node which is assumed to already be in a list.
It does not allocate a new node, but takes an already allocated node, thus allowing to use it (together with
a procedure to remove a node from a list) for splicing a node from one list to another. *)
procedure InsertAfter(listnode, newnode: pCharNode);
begin
newnode^.next := listnode^.next;
listnode^.next := newnode;
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
| #Forth | Forth | : sleep ( ms -- )
." Sleeping..."
ms
." awake." cr ; |
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
| #Fortran | Fortran | program test_sleep
implicit none
integer :: iostat
integer :: seconds
character (32) :: argument
if (iargc () == 1) then
call getarg (1, argument)
read (argument, *, iostat = iostat) seconds
if (iostat == 0) then
write (*, '(a)') 'Sleeping...'
call sleep (seconds)
write (*, '(a)') 'Awake!'
end if
end if
end program test_sleep |
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.
| #X86_Assembly | X86 Assembly | .model tiny
.code
.486
org 100h
start: mov si, offset array
mov ax, 40 ;length of array (not including $)
call bsort
mov dx, si ;point to array
mov ah, 09h ;display it as a string
int 21h
ret
array db "Pack my box with five dozen liquor jugs.$"
;Bubble sort: si = array addrsss, ax = number of bytes
bsort: pusha
xchg cx, ax ;get size of array N
dec cx ;for J:= N-1 downto 0
bs10: xor bx, bx ;for I:= 0 to J-1
bs20: mov ax, [bx+si]
cmp al, ah ;if A(I) > A(I+1) then
jbe bs30
xchg al, ah ; swap bytes
mov [bx+si], ax
bs30: inc bx ;next I
cmp bx, cx
jb bs20
loop bs10
popa
ret
end start |
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 | #Scheme | Scheme | (cons value 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 | #Sidef | Sidef | var node = Hash.new(
data => 'say what',
next => foo_node,
);
node{:next} = bar_node; # mutable |
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 | #SSEM | SSEM | 01000000000000000000000000000000 26. 2
01111000000000000000000000000000 27. 30
10000000000000000000000000000000 28. 1
01011000000000000000000000000000 29. 26
11000000000000000000000000000000 30. 3
00000000000000000000000000000000 31. 0 |
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.
| #D | D | module winapp ;
import dfl.all ;
import std.string ;
class MainForm: Form {
Label label ;
Button button ;
this() {
width = 240 ;
with(label = new Label) {
text = "There have been no clicks yet" ;
dock = DockStyle.TOP ;
parent = this ;
}
with(button = new Button) {
dock = DockStyle.BOTTOM ;
text = "Click Me" ;
parent = this ;
click ~= &onClickButton ;
}
height = label.height + button.height + 36 ;
}
private void onClickButton(Object sender, EventArgs ea) {
static int count = 0 ;
label.text = "You had been clicked me " ~ std.string.toString(++count) ~ " times." ;
}
}
void main() {
Application.run(new MainForm);
} |
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
| #ooRexx | ooRexx | list=.list~of('A','B','X')
say "Manual list traversal"
index=list~first
loop while index \== .nil
say list~at(index)
index = list~next(index)
end
say
say "Do ... Over traversal"
do value over list
say value
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
| #Perl | Perl | my @l = ($A, $B);
push @l, $C, splice @l, 1; |
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
| #Phix | Phix | with javascript_semantics
enum NEXT,DATA
constant empty_sll = {{1}}
sequence sll = deep_copy(empty_sll)
procedure insert_after(object data, integer pos=length(sll))
sll = append(sll,{sll[pos][NEXT],data})
sll[pos][NEXT] = length(sll)
end procedure
insert_after("ONE")
insert_after("TWO")
insert_after("THREE")
?sll
|
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
| #FreeBASIC | FreeBASIC | ' FB 1.05.0 Win64
Dim ms As UInteger
Input "Enter number of milliseconds to sleep" ; ms
Print "Sleeping..."
Sleep ms, 1 '' the "1" means Sleep can't be interrupted with a keystroke
Print "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
| #Frink | Frink |
do
t = eval[input["Enter amount of time to sleep: ", "1 second"]]
while ! (t conforms time)
println["Sleeping..."]
sleep[t]
println["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.
| #Xojo | Xojo | Dim temp, count As Integer
Dim isDirty As Boolean
count = Ubound(list) // count the array size
// loop through until we don't move any numbers... this means we are sorted
Do
isDirty = False // we haven't touched anything yet
For i As Integer = 1 To count - 1 // loop through all the numbers
If list(i) > list(i + 1) Then // if the right number is smaller then the left.. swap
temp = list(i + 1)
list(i + 1) = list(i)
list(i) = temp
isDirty = True // we touched the data so mark it as dirty
End
Next
Loop Until isDirty = False // if we made it without touching the data then we are done |
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 | #Stata | Stata | struct item {
transmorphic scalar value
pointer(struct item scalar) scalar next
}
struct list {
pointer(struct item scalar) scalar head, tail
} |
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 | #Swift | Swift | class Node<T>{
var data:T?=nil
var next:Node?=nil
init(input:T){
data=input
next=nil
}
}
|
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 | #Tcl | Tcl | oo::class create List {
variable content next
constructor {value {list ""}} {
set content $value
set next $list
}
method value args {
set content {*}$args
}
method attach {list} {
set next $list
}
method detach {} {
set next ""
}
method next {} {
return $next
}
method print {} {
for {set n [self]} {$n ne ""} {set n [$n next]} {
lappend values [$n value]
}
return $values
}
} |
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.
| #Delphi | Delphi | -- begin file --
Program SingleWinApp ;
// This is the equivalent of the C #include
Uses Forms, Windows, Messages, Classes, Graphics, Controls, StdCtrls ;
type
// The only reason for this declaration is to allow the connection of the
// on click method to the forms button object. This class declaration adds
// a procedure.
TMainForm class(tform)
Procedure AddClicks(sender : tObject);
end;
// Use these globals.
var
MainForm : tForm ;
aLabel : tLabel ;
aButton : tButton ;
i : integer = 0 ;
// This is the Method call that we connect to the button object
// to start counting the clicks.
Procedure tMainForm.AddClicks(sender :tObject)
begin
inc(i);
aLabel.Caption := IntToStr(i) + ' Clicks since startup' ;
end;
Begin
// Do all the behind the scenes stuff that sets up the Windows environment
Application.Initialize ;
// Create the form
// Forms can either be created with an owner, like I have done here, or with
// the owner set to Nil. In pascal (all versions of Borland) '''NIL''' is a
// reserved, (the equivalent of '''NULL''' in Ansi C) word and un-sets any pointer
// variable. Setting the owner to the application object will ensure that the form is
// freed by the application object when the application shuts down. If I had set
// the owner to NIL then i would have had to make sure I freed the form explicitly
// or it would have been orphaned, thus creating a memory leak.
// I must direct your attention to the CreateNew constructor. This is
// a non standard usage. Normally the constructor Create() will call this
// as part of the initialization routine for the form. Normally as you drop
// various components on a form in deign mode, a DFM file is created with
// all the various initial states of the controls. This bypasses the
// DFM file altogether although all components AND the form are created
// with default values. (see the Delphi help file).
MainForm := tMainForm.CreateNew(Application);
MainForm.Parent := Application ;
MainForm.Position := poScreenCenter ;
MainForm.Caption := 'Single Window Application' ;
// Create the Label, set its owner as MaiaForm
aLabel := tLabel.Create(mainForm);
aLabel.Parent := MainForm;
aLabel.Caption := IntToStr(i) + ' Clicks since startup' ;
aLabel.Left := 20 ;
aLabel.Top := MainForm.ClientRect.Bottom div 2 ;
// Create the button, set its owner to MainForm
aButton := tButton.Create(MainForm);
aButton.Parent := MainForm ;
aButton.Caption := 'Click Me!';
aButton.Left := (MainForm.ClientRect.Right div 2)-(aButton.Width div 2 );
aButton.Top := MainForm.ClientRect.Bottom - aButton.Height - 10 ;
aButton.OnClick := AddClicks ;
// Show the main form, Modaly. The ONLY reason to do this is because in this
// demonstration if you only call the SHOW method, the form will appear and
// disappear in a split second.
MainForm.ShowModal ;
Application.Run ;
end. // Program |
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
| #Pascal | Pascal | <@ LETCNSLSTLIT>public holidays|開國紀念日^和平紀念日^婦女節、兒童節合併假期^清明節^國慶日^春節^端午節^中秋節^農曆除夕</@>
<@ OMT>From First to Last</@>
<@ ITEFORSZELSTLIT>public holidays|
<@ SAYLST>...</@><@ ACTMOVFWDLST>...</@>
</@>
<@ OMT>From Last to First (pointer is still at end of list)</@>
<@ ITEFORSZELSTLIT>public holidays|
<@ SAYLST>...</@><@ ACTMOVBKWLST>...</@>
</@> |
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
| #Peloton | Peloton | <@ LETCNSLSTLIT>public holidays|開國紀念日^和平紀念日^婦女節、兒童節合併假期^清明節^國慶日^春節^端午節^中秋節^農曆除夕</@>
<@ OMT>From First to Last</@>
<@ ITEFORSZELSTLIT>public holidays|
<@ SAYLST>...</@><@ ACTMOVFWDLST>...</@>
</@>
<@ OMT>From Last to First (pointer is still at end of list)</@>
<@ ITEFORSZELSTLIT>public holidays|
<@ SAYLST>...</@><@ ACTMOVBKWLST>...</@>
</@> |
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
| #PicoLisp | PicoLisp | (de insertAfter (Item Lst New)
(when (member Item Lst)
(con @ (cons New (cdr @))) )
Lst ) |
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
| #PL.2FI | PL/I |
/* Let H be a pointer to a node in a one-way-linked list. */
/* Insert an element, whose value is given by variable V, following that node. */
allocate node set (Q);
node.p = H; /* The new node now points at the list where we want to insert it. */
node.value = V;
H->p = Q; /* Break the list at H, and point it at the 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
| #Pop11 | Pop11 | define insert_into_list(anchor, x);
cons(x, back(anchor)) -> back(anchor);
enddefine;
;;; Build inital list
lvars l1 = cons("a", []);
insert_into_list(l1, "b");
;;; insert c
insert_into_list(l1, "c"); |
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
| #Go | Go | package main
import "time"
import "fmt"
func main() {
fmt.Print("Enter number of seconds to sleep: ")
var sec float64
fmt.Scanf("%f", &sec)
fmt.Print("Sleeping…")
time.Sleep(time.Duration(sec * float64(time.Second)))
fmt.Println("\nAwake!")
} |
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
| #Groovy | Groovy | def sleepTest = {
println("Sleeping...")
sleep(it)
println("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.
| #XPL0 | XPL0 | include c:\cxpl\codes; \intrinsic 'code' declarations
string 0; \use zero-terminated strings
proc BSort(A, N); \Bubble sort array in ascending order
char A; \address of array
int N; \number of items in array (size)
int I, J, T;
[for J:= N-1 downto 0 do
for I:= 0 to J-1 do
if A(I) > A(I+1) then
[T:= A(I); A(I):= A(I+1); A(I+1):= T]; \swap items
]; \BSort
func StrLen(Str); \Return number of characters in an ASCIIZ string
char Str;
int I;
for I:= 0 to -1>>1-1 do
if Str(I) = 0 then return I;
char Str;
[Str:= "Pack my box with five dozen liquor jugs.";
BSort(Str, StrLen(Str));
Text(0, Str); CrLf(0);
] |
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 | #Wren | Wren | import "/llist" for Node
var n1 = Node.new(1)
var n2 = Node.new(2)
n1.next = n2
System.print(["node 1", "data = %(n1.data)", "next = %(n1.next)"])
System.print(["node 2", "data = %(n2.data)", "next = %(n2.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 | #X86_Assembly | X86 Assembly |
; x86_64 Linux NASM
; Linked_List_Definition.asm
%ifndef LinkedListDefinition
%define LinkedListDefinition
struc link
value: resd 1
next: resq 1
linkSize:
endstruc
%endif
|
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.
| #E | E | when (currentVat.morphInto("awt")) -> {
var clicks := 0
def w := <swing:makeJFrame>("Rosetta Code 'Simple Windowed Application'")
w.setContentPane(JPanel`
${def l := <swing:makeJLabel>("There have been no clicks yet.")} $\
${def b := <swing:makeJButton>("Click Me")}
`)
b.addActionListener(def _ {
to actionPerformed(_) {
clicks += 1
l.setText(`Number of clicks: $clicks`)
}
})
w.pack()
w.show()
} |
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
| #Perl | Perl | package SSL_Node;
use strict;
use Class::Tiny qw( val next );
sub BUILD {
my $self = shift;
exists($self->{val}) or die "Must supply 'val'";
if (exists $self->{next}) {
ref($self->{next}) eq 'SSL_Node'
or die "If supplied, 'next' must be an SSL_Node";
}
return;
}
package main;
use strict;
# Construct an example list,
my @vals = 1 .. 10;
my $countdown = SSL_Node->new(val => shift(@vals));
while (@vals) {
my $head = SSL_Node->new(val => shift(@vals), next => $countdown);
$countdown = $head;
}
# ...then traverse it.
my $node = $countdown;
while ($node) {
print $node->val, "... ";
$node = $node->next;
}
print "\n"; |
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
| #PureBasic | PureBasic | Procedure insertAfter(Value, *node.MyData = #Null)
Protected *newNode.MyData = AllocateMemory(SizeOf(MyData))
If *newNode
If *node
*newNode\next = *node\next
*node\next = *newNode
EndIf
*newNode\Value = Value
EndIf
ProcedureReturn *newNode ;return pointer to newnode
EndProcedure
Define *SL_List.MyData, a = 1, b = 2, c = 3
*SL_List = insertAfter(a) ;start the list
insertAfter(b, *SL_List) ;insert after head of list
insertAfter(c, *SL_List) ;insert after head of list and before tail |
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
| #Python | Python | def chain_insert(lst, at, item):
while lst is not None:
if lst[0] == at:
lst[1] = [item, lst[1]]
return
else:
lst = lst[1]
raise ValueError(str(at) + " not found")
chain = ['A', ['B', None]]
chain_insert(chain, 'A', 'C')
print chain |
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
| #Haskell | Haskell | import Control.Concurrent
main = do seconds <- readLn
putStrLn "Sleeping..."
threadDelay $ round $ seconds * 1000000
putStrLn "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
| #HicEst | HicEst | DLG(NameEdit = milliseconds, Button = "Go to sleep")
WRITE(StatusBar) "Sleeping ... "
SYSTEM(WAIT = milliseconds)
WRITE(Messagebox) "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.
| #Yabasic | Yabasic | // Animated sort.
// Original idea by William Tang, obtained from MicroHobby 25 Years (https://microhobby.speccy.cz/zxsf/MH-25Years.pdf)
clear screen
n=15 : m=18 : y=9 : t$=chr$(17)+chr$(205)+chr$(205)
dim p(n), p$(n)
for x=1 TO n
p(x)=ran(15)+1
p$(x)=str$(p(x),"##.######")
print at(0,x) p$(x)
next x
for j=1 to n-1
for i=j+1 to n
l=n+j-i+1
if p(j) > p(l) then
print color("yellow","red") at(0,j) p$(j)
if l<>m then
for x=m to l step sig(l-m): print at(18,x) t$ : print at (18,x+sig(m-l)) " " : pause .02 : next x
end if
for x=17 TO y step -1 : print at(x,l) t$+" " : pause .02 : next x
for x=0 TO 10 : print at(x,l) " "+p$(l)+t$ : pause .02 : next x
for x=l TO j STEP -1 : print at(11,x) p$(l)+t$ : print at(11,x+1) " " : pause .02 : next x
print at(0,j) " "
for x=j+1 TO l-1 : print color("yellow","red") at(0,x) p$(j) : pause .02 : print at(0,x) p$(x) : pause .02 : next x
print at(0,l) p$(j)
for x=10 TO 0 step -1 : print at(x,j) p$(l)+t$+" " : pause .02 : next x
for x=y TO 17 : print at(x,j) " "+t$ : pause .02 : next x
m=j
t=p(l) : tem$=p$(l)
p(l)=p(j) : p$(l)=p$(j)
p(j)=t : p$(j)=tem$
end if
pause .02
next i
next j
for x=m TO 18 : print at(18,x-1) " " : print at(18,x) t$ : pause .02 : next 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 | #XPL0 | XPL0 | def \Node\ Link, Data; \linked list element definition
int Node, List, N;
def IntSize = 4; \number of bytes in an integer
[List:= 0; \List is initially empty
for N:= 1 to 10 do \build linked list, starting at the end
[Node:= Reserve(IntSize*2); \get some memory to store Link and Data
Node(Link):= List;
Node(Data):= N*N; \insert example data
List:= Node; \List now points to newly created node
];
Node:= List; \traverse the linked list
while Node # 0 do
[IntOut(0, Node(Data)); \display the example data
ChOut(0, ^ );
Node:= Node(Link); \move to next node
];
] |
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 | #Zig | Zig | const std = @import("std");
var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator);
const allocator = arena.allocator();
pub fn LinkedList(comptime Value: type) type {
return struct {
const This = @This();
const Node = struct {
value: Value,
next: ?*Node,
};
head: ?*Node,
tail: ?*Node,
pub fn init() This {
return LinkedList(Value) {
.head = null,
.tail = null,
};
}
pub fn add(this: *This, value: Value) !void {
var newNode = try allocator.create(Node);
newNode.* = .{ .value = value, .next = null };
if (this.tail) |tail| {
tail.next = newNode;
this.tail = newNode;
} else if (this.head) |head| {
head.next = newNode;
this.tail = newNode;
} else {
this.head = newNode;
}
}
};
} |
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 | #zkl | zkl | List(1,"two",3.14); L(1,"two",3.14);
ROList(fcn{"foobar"}); T('+); |
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.
| #EchoLisp | EchoLisp |
(define (ui-add-button text) ;; helper
(define b (ui-create-element "button" '((type "button"))))
(ui-set-html b text)
(ui-add b))
(define (panel )
(ui-clear)
(define *clicks* 0)
(define text (ui-create-element "span" '((style "font-weight:bold"))))
(ui-add text)
(ui-set-html text "No click yet")
(define btn (ui-add-button "Click-me"))
(define (count-clicks elem)
(++ *clicks*)
(ui-set-html text *clicks*))
(ui-on-click btn count-clicks)
(stdout-hide #t)
(stdin-hide #t)) ;; end panel definition
(panel)
|
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
| #Phix | Phix | with javascript_semantics
enum NEXT,DATA
constant empty_sll = {{1}}
sequence sll = deep_copy(empty_sll)
procedure insert_after(object data, integer pos=length(sll))
sll = append(sll,{sll[pos][NEXT],data})
sll[pos][NEXT] = length(sll)
end procedure
insert_after("ONE")
insert_after("TWO")
insert_after("THREE")
?sll
procedure show()
integer idx = sll[1][NEXT]
while idx!=1 do
?sll[idx][DATA]
idx = sll[idx][NEXT]
end while
end procedure
show()
|
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
| #Racket | Racket |
#lang racket
;; insert b after a in a mutable list (assumes that a is in the input list)
(define (insert-after! list a b)
(if (equal? (mcar list) a)
(set-mcdr! list (mcons b (mcdr list)))
(insert-after! (mcdr list) a b)))
(define l (mcons 1 (mcons 2 (mcons 3 '()))))
(insert-after! l 2 2.5)
l ; -> (mcons 1 (mcons 2 (mcons 2.5 (mcons 3))))
|
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
| #Raku | Raku | method insert ($value) {
$.next = Cell.new(:$value, :$.next)
} |
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
| #Icon_and_Unicon | Icon and Unicon | procedure main()
repeat {
writes("Enter number of seconds to sleep :")
s := reads()
if s = ( 0 < integer(s)) then break
}
write("\nSleeping for ",s," seconds.")
delay(1000 * s)
write("Awake!")
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.
| #Yorick | Yorick | func bubblesort(&items) {
itemCount = numberof(items);
do {
hasChanged = 0;
itemCount--;
for(index = 1; index <= itemCount; index++) {
if(items(index) > items(index+1)) {
items([index,index+1]) = items([index+1,index]);
hasChanged = 1;
}
}
} while(hasChanged);
} |
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.
| #Elena | Elena | import forms;
import extensions;
public class MainWindow : SDIDialog
{
Label lblClicks;
Button btmClickMe;
//Store how much clicks the user doed
int clicksCount;
constructor new()
<= new()
{
lblClicks := Label.new();
btmClickMe := Button.new();
clicksCount := 0;
self
.appendControl(lblClicks)
.appendControl(btmClickMe);
self.Caption := "Rosseta Code";
self.setRegion(100, 100, 160, 80);
lblClicks.Caption := "Clicks: 0";
lblClicks.setRegion(10, 2, 160, 20);
btmClickMe.Caption := "Click me";
btmClickMe.setRegion(7, 20, 140, 30);
btmClickMe.onClick := (args){ self.onButtonClick(); };
}
private onButtonClick()
{
clicksCount := clicksCount + 1;
lblClicks.Caption := "Clicks: " + clicksCount.toString();
}
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.