Sort disjoint sublist: Difference between revisions

m
m (→‎{{header|AppleScript}}: Restored the "ASObjC/functional" index subheading given to the original script as it's accurate, can't possibly have offended the original poster, and explains the differences between that and the vanilla script just added.)
m (→‎{{header|Wren}}: Minor tidy)
 
(40 intermediate revisions by 26 users not shown)
Line 1:
{{task|Sorting Algorithms}}
{{Sorting Algorithm}}
[[Category:Sorting]]
{{task|Sorting Algorihms}}
 
Given a list of values and a set of integer indices into that value list, the task is to sort the values at the given indices, while preserving the values at indices outside the set of those to be sorted.
Line 23:
*   [[Order disjoint list items]]
<br><br>
 
=={{header|11l}}==
{{trans|Python}}
 
<syntaxhighlight lang="11l">F sort_disjoint_sublist(&data, indices)
V sindices = sorted(indices)
V values = sorted(sindices.map(i -> @data[i]))
L(index, value) zip(sindices, values)
data[index] = value
 
V d = [7, 6, 5, 4, 3, 2, 1, 0]
V i = [6, 1, 7]
sort_disjoint_sublist(&d, i)
print(d)</syntaxhighlight>
 
{{out}}
<pre>
[7, 0, 5, 4, 3, 2, 1, 6]
</pre>
=={{header|AArch64 Assembly}}==
{{works with|as|Raspberry Pi 3B version Buster 64 bits <br> or android 64 bits with application Termux }}
<syntaxhighlight lang AArch64 Assembly>
/* ARM assembly AARCH64 Raspberry PI 3B */
/* program sublistSort64.s */
 
/************************************/
/* Constantes */
/************************************/
/* for this file see task include a file in language AArch64 assembly*/
.include "../includeConstantesARM64.inc"
/*********************************/
/* Initialized data */
/*********************************/
.data
szMessStart: .asciz "Program 64 bits start.\n"
sMessResult: .ascii "Value : "
sMessValeur: .fill 11, 1, ' ' // size => 11
szCarriageReturn: .asciz "\n"
.align 4
ArrayNumber: .quad 7, 6, 5, 4, 3, 2, 1, 0
.equ NBELEMENTS, (. - ArrayNumber) / 8
ArrayIndex: .quad 6,1,7
.equ NBELEMINDEX, (. - ArrayIndex) / 8
/*********************************/
/* UnInitialized data */
/*********************************/
.bss
ArrayExtract: .skip 8 * NBELEMINDEX
/*********************************/
/* code section */
/*********************************/
.text
.global main
main:
ldr x0,qAdrszMessStart
bl affichageMess
ldr x4,qAdrArrayNumber // number array address
ldr x5,qAdrArrayIndex // index array address
ldr x6,qAdrArrayExtract // extract array address
mov x3,#0 // index
1:
ldr x0,[x5,x3,lsl #3] // load index
ldr x1,[x4,x0,lsl #3] // load value of index
str x1,[x6,x3,lsl #3] // store value in array extract
add x3,x3,#1 // increment index
cmp x3,#NBELEMINDEX // end array index ?
blt 1b // no -> loop
 
mov x0,x5 // index array address
mov x1,#0 // first element
mov x2,#NBELEMINDEX // array size
bl insertionSort
mov x0,x6 // extract array address
mov x1,#0 // first element
mov x2,#NBELEMINDEX // array size
bl insertionSort
 
mov x3,#0 // init index
2:
ldr x0,[x6,x3,lsl #3] // load value of array extract
ldr x1,[x5,x3,lsl #3] // load index
str x0,[x4,x1,lsl #3] // store value in number array in index place
add x3,x3,#1 // increment indice
cmp x3,#NBELEMINDEX
blt 2b
 
mov x0,x4 // number array address
bl displayArray
100: // standard end of the program
mov x0, #0 // return code
mov x8, #EXIT // request to exit program
svc #0 // perform the system call
qAdrsMessValeur: .quad sMessValeur
qAdrszMessStart: .quad szMessStart
qAdrszCarriageReturn: .quad szCarriageReturn
qAdrsMessResult: .quad sMessResult
qAdrArrayNumber: .quad ArrayNumber
qAdrArrayIndex: .quad ArrayIndex
qAdrArrayExtract: .quad ArrayExtract
/******************************************************************/
/* insertion sort */
/******************************************************************/
/* x0 contains the address of table */
/* x1 contains the first element */
/* x2 contains the number of element */
insertionSort:
stp x1,lr,[sp,-16]! // save registers
stp x2,x3,[sp,-16]!
stp x4,x5,[sp,-16]!
stp x6,x7,[sp,-16]!
add x3,x1,#1 // start index i
1: // start loop
ldr x4,[x0,x3,lsl #3] // load value A[i]
sub x5,x3,#1 // index j
2:
ldr x6,[x0,x5,lsl #3] // load value A[j]
cmp x6,x4 // compare value
ble 3f
add x5,x5,#1 // increment index j
str x6,[x0,x5,lsl #3] // store value A[j+1]
subs x5,x5,#2 // j = j - 1
bge 2b // loop if j >= 0
3:
add x5,x5,#1 // increment index j
str x4,[x0,x5,lsl #3] // store value A[i] in A[j+1]
add x3,x3,#1 // increment index i
cmp x3,x2 // end ?
blt 1b // no -> loop
 
100:
ldp x6,x7,[sp],16
ldp x4,x5,[sp],16
ldp x2,x3,[sp],16
ldp x1,lr,[sp],16
ret
 
/******************************************************************/
/* Display table elements */
/******************************************************************/
/* x0 contains the address of array */
displayArray:
stp x1,lr,[sp,-16]!
stp x2,x3,[sp,-16]!
mov x2,x0 // table address
mov x3,#0
1: // loop display table
ldr x0,[x2,x3,lsl #3]
ldr x1,qAdrsMessValeur // display value
bl conversion10 // call function
ldr x0,qAdrsMessResult
bl affichageMess // display message
ldr x0,qAdrszCarriageReturn
bl affichageMess
add x3,x3,#1
cmp x3,#NBELEMENTS
blt 1b
ldr x0,qAdrszCarriageReturn
bl affichageMess
100:
ldp x2,x3,[sp],16
ldp x1,lr,[sp],16
ret
 
/***************************************************/
/* ROUTINES INCLUDE */
/***************************************************/
/* for this file see task include a file in language AArch64 assembly*/
.include "../includeARM64.inc"
</syntaxhighlight>
{{Out}}
<pre>
Program 64 bits start.
Value : 7
Value : 0
Value : 5
Value : 4
Value : 3
Value : 2
Value : 1
Value : 6
</pre>
=={{header|Action!}}==
<syntaxhighlight lang="action!">PROC PrintArray(INT ARRAY a INT size)
INT i
 
Put('[)
FOR i=0 TO size-1
DO
IF i>0 THEN Put(' ) FI
PrintI(a(i))
OD
Put(']) PutE()
RETURN
 
BYTE FUNC InSet(INT ARRAY s INT size INT v)
INT i
 
FOR i=0 TO size-1
DO
IF s(i)=v THEN
RETURN (1)
FI
OD
RETURN (0)
 
PROC Sort(INT ARRAY arr INT arrSize
INT ARRAY ind INT indSize)
INT i,j,minpos,tmp
 
FOR i=0 TO arrSize-2
DO
IF InSet(ind,indSize,i) THEN
minpos=i
FOR j=i+1 TO arrSize-1
DO
IF InSet(ind,indSize,j)=1 AND arr(minpos)>arr(j) THEN
minpos=j
FI
OD
IF minpos#i THEN
tmp=arr(i)
arr(i)=arr(minpos)
arr(minpos)=tmp
FI
FI
OD
RETURN
 
PROC Test(INT ARRAY arr INT arrSize
INT ARRAY ind INT indSize)
PrintE("Array before sort:")
PrintArray(arr,arrSize)
PrintE("Indices:")
PrintArray(ind,indSize)
Sort(arr,arrSize,ind,indSize)
PrintE("Array after sort:")
PrintArray(arr,arrSize)
RETURN
 
PROC Main()
INT ARRAY
arr(8)=[7 6 5 4 3 2 1 0],
ind(3)=[6 1 7]
Test(arr,8,ind,3)
RETURN</syntaxhighlight>
{{out}}
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Sort_disjoint_sublist.png Screenshot from Atari 8-bit computer]
<pre>
Array before sort:
[7 6 5 4 3 2 1 0]
Indices:
[6 1 7]
Array after sort:
[7 0 5 4 3 2 1 6]
</pre>
 
=={{header|Ada}}==
<langsyntaxhighlight Adalang="ada">with Ada.Text_IO, GNAT.Bubble_Sort;
use Ada.Text_IO;
 
Line 81 ⟶ 342:
New_Line;
 
end DisjointSort;</langsyntaxhighlight>
 
=={{header|ALGOL W}}==
Uses the quicksort procedure from the Sorting Algorithms/Quicksort task and a variant for indexed sorting.
<syntaxhighlight lang="algolw">begin % sort a disjoint sub-set of a list %
% Quicksorts in-place the array of integers v, from lb to ub %
procedure quicksort ( integer array v( * )
; integer value lb, ub
) ;
if ub > lb then begin
% more than one element, so must sort %
integer left, right, pivot;
left := lb;
right := ub;
% choosing the middle element of the array as the pivot %
pivot := v( left + ( ( right + 1 ) - left ) div 2 );
while begin
while left <= ub and v( left ) < pivot do left := left + 1;
while right >= lb and v( right ) > pivot do right := right - 1;
left <= right
end do begin
integer swap;
swap := v( left );
v( left ) := v( right );
v( right ) := swap;
left := left + 1;
right := right - 1
end while_left_le_right ;
quicksort( v, lb, right );
quicksort( v, left, ub )
end quicksort ;
% Quicksorts in-place the array of integers v, using %
% the indxexes in unsortedIndexes which has bounds lb to ub %
% it is assumed all elements of unsortedIndexes are in the %
% range for subscripts of v %
procedure indexedQuicksort ( integer array v, unsortedIndexes ( * )
; integer value lb, ub
) ;
if ub > lb then begin
% more than one element, so must sort %
integer array indexes ( lb :: ub );
integer left, right, pivot, p;
% sort the indexes %
for i := lb until ub do indexes( i ) := unsortedIndexes( i );
quicksort( indexes, lb, ub );
% sort the indexed items of the v array %
left := lb;
right := ub;
% choosing the middle element of the array as the pivot %
p := left + ( ( ( right + 1 ) - left ) div 2 );
pivot := v( indexes( p ) );
while begin
while left <= ub and v( indexes( left ) ) < pivot do left := left + 1;
while right >= lb and v( indexes( right ) ) > pivot do right := right - 1;
left <= right
end do begin
integer swap;
swap := v( indexes( left ) );
v( indexes( left ) ) := v( indexes( right ) );
v( indexes( right ) ) := swap;
left := left + 1;
right := right - 1
end while_left_le_right ;
indexedQuicksort( v, indexes, lb, right );
indexedQuicksort( v, indexes, left, ub )
end indexedQuicksort ;
begin % task %
integer array indexes ( 0 :: 2 );
integer array values ( 0 :: 7 );
integer aPos;
aPos := 0;
for v := 7, 6, 5, 4, 3, 2, 1, 0 do begin
values( aPos ) := v;
aPos := aPos + 1
end for_v ;
indexes( 0 ) := 6;
indexes( 1 ) := 1;
indexes( 2 ) := 7;
i_w := 1; s_w := 0; % set output formatting %
write( "[" );
for v := 0 until 7 do writeon( " ", values( v ) );
writeon( " ]" );
indexedQuicksort( values, indexes, 0, 2 );
writeon( " -> [" );
for v := 0 until 7 do writeon( " ", values( v ) );
writeon( " ]" )
end
end.</syntaxhighlight>
{{out}}
<pre>
[ 7 6 5 4 3 2 1 0 ] -> [ 7 0 5 4 3 2 1 6 ]
</pre>
 
=={{header|APL}}==
<langsyntaxhighlight lang="apl">
∇SDS[⎕]∇
Line 91 ⟶ 443:
[2] Z←L
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 101 ⟶ 453:
 
=={{header|AppleScript}}==
===ASObjC/functionalFunctional===
 
Uses Foundation framework (through the ObjC interface), and works with versions of AppleScript from OS X 10.10 onwards.
 
<langsyntaxhighlight AppleScriptlang="applescript">use AppleScript version "2.4"
use framework "Foundation"
use scripting additions
Line 301 ⟶ 653:
return lst
end tell
end zipWith</langsyntaxhighlight>
{{Out}}
<langsyntaxhighlight AppleScriptlang="applescript">{7, 0, 5, 4, 3, 2, 1, 6}</langsyntaxhighlight>
 
===VanillaIdiomatic, vanilla===
 
This works with Mac OS 10.9 or later, and with older systems if an earlier method's used to load the insertion sort handler or that handler's copied into the script.
 
<langsyntaxhighlight lang="applescript">use AppleScript version "2.3.1" -- Mac OS 10.9 (Mavericks) or later.
use sorter : script "Insertion sort" -- https://www.rosettacode.org/wiki/Sorting_algorithms/Insertion_sort#AppleScript.
 
Line 335 ⟶ 687:
set indices to {7, 2, 8} -- AppleScript indices are one-based.
sortValuesAtIndices(values, indices)
return values</langsyntaxhighlight>
 
{{output}}
<langsyntaxhighlight lang="applescript">{7, 0, 5, 4, 3, 2, 1, 6}</langsyntaxhighlight>
=={{header|ARM Assembly}}==
{{works with|as|Raspberry Pi <br> or android 32 bits with application Termux}}
<syntaxhighlight lang ARM Assembly>
/* ARM assembly Raspberry PI */
/* program sublistSort.s */
 
/************************************/
=={{header|BBC BASIC}}==
/* Constantes */
/************************************/
/* for constantes see task include a file in arm assembly */
.include "../constantes.inc"
/*********************************/
/* Initialized data */
/*********************************/
.data
szMessStart: .asciz "Program 32 bits start.\n"
sMessResult: .ascii "Value : "
sMessValeur: .fill 11, 1, ' ' @ size => 11
szCarriageReturn: .asciz "\n"
.align 4
ArrayNumber: .int 7, 6, 5, 4, 3, 2, 1, 0
.equ NBELEMENTS, (. - ArrayNumber) / 4
ArrayIndex: .int 6,1,7
.equ NBELEMINDEX, (. - ArrayIndex) / 4
/*********************************/
/* UnInitialized data */
/*********************************/
.bss
ArrayExtract: .skip 4 * NBELEMINDEX
/*********************************/
/* code section */
/*********************************/
.text
.global main
main:
ldr r0,iAdrszMessStart
bl affichageMess
ldr r4,iAdrArrayNumber @ number array address
ldr r5,iAdrArrayIndex @ index array address
ldr r6,iAdrArrayExtract @ extract array address
mov r3,#0 @ index
1:
ldr r0,[r5,r3,lsl #2] @ load index
ldr r1,[r4,r0,lsl #2] @ load value of index
str r1,[r6,r3,lsl #2] @ store value in array extract
add r3,r3,#1 @ increment index
cmp r3,#NBELEMINDEX @ end array index ?
blt 1b @ no -> loop
 
mov r0,r5 @ index array address
mov r1,#0 @ first element
mov r2,#NBELEMINDEX @ array size
bl insertionSort
mov r0,r6 @ extract array address
mov r1,#0 @ first element
mov r2,#NBELEMINDEX @ array size
bl insertionSort
 
mov r3,#0 @ init index
2:
ldr r0,[r6,r3,lsl #2] @ load value of array extract
ldr r1,[r5,r3,lsl #2] @ load index
str r0,[r4,r1,lsl #2] @ store value in number array in index place
add r3,r3,#1 @ increment indice
cmp r3,#NBELEMINDEX
blt 2b
 
mov r0,r4 @ number array address
bl displayArray
100: @ standard end of the program
mov r0, #0 @ return code
mov r7, #EXIT @ request to exit program
svc #0 @ perform the system call
iAdrsMessValeur: .int sMessValeur
iAdrszMessStart: .int szMessStart
iAdrszCarriageReturn: .int szCarriageReturn
iAdrsMessResult: .int sMessResult
iAdrArrayNumber: .int ArrayNumber
iAdrArrayIndex: .int ArrayIndex
iAdrArrayExtract: .int ArrayExtract
/******************************************************************/
/* insertion sort */
/******************************************************************/
/* r0 contains the address of table */
/* r1 contains the first element */
/* r2 contains the number of element */
insertionSort:
push {r2-r6,lr} @ save registers
add r3,r1,#1 @ start index i
1: @ start loop
ldr r4,[r0,r3,lsl #2] @ load value A[i]
sub r5,r3,#1 @ index j
2:
ldr r6,[r0,r5,lsl #2] @ load value A[j]
cmp r6,r4 @ compare value
ble 3f
add r5,#1 @ increment index j
str r6,[r0,r5,lsl #2] @ store value A[j+1]
subs r5,#2 @ j = j - 1
bge 2b @ loop if j >= 0
3:
add r5,#1 @ increment index j
str r4,[r0,r5,lsl #2] @ store value A[i] in A[j+1]
add r3,#1 @ increment index i
cmp r3,r2 @ end ?
blt 1b @ no -> loop
 
100:
pop {r2-r6,pc}
 
/******************************************************************/
/* Display table elements */
/******************************************************************/
/* r0 contains the address of table */
displayArray:
push {r0-r3,lr} @ save registers
mov r2,r0 @ table address
mov r3,#0
1: @ loop display table
ldr r0,[r2,r3,lsl #2]
ldr r1,iAdrsMessValeur @ display value
bl conversion10 @ call function
ldr r0,iAdrsMessResult
bl affichageMess @ display message
add r3,#1
cmp r3,#NBELEMENTS
blt 1b
ldr r0,iAdrszCarriageReturn
bl affichageMess
100:
pop {r0-r3,lr}
bx lr
 
/***************************************************/
/* ROUTINES INCLUDE */
/***************************************************/
/* for this file see task include a file in language ARM assembly*/
.include "../affichage.inc"
</syntaxhighlight>
{{Out}}
<pre>
Program 32 bits start.
Value : 7
Value : 0
Value : 5
Value : 4
Value : 3
Value : 2
Value : 1
Value : 6
</pre>
=={{header|Arturo}}==
 
<syntaxhighlight lang="rebol">sortDisjoint: function [data, indices][
result: new data
inds: new indices
sort 'inds
 
vals: new []
loop inds 'i -> 'vals ++ result\[i]
sort 'vals
 
loop.with:'j inds 'i -> result\[i]: vals\[j]
return result
]
d: [7 6 5 4 3 2 1 0]
print sortDisjoint d [6 1 7]</syntaxhighlight>
 
{{out}}
 
<pre>7 0 5 4 3 2 1 6</pre>
 
=={{header|ATS}}==
 
Much of the code here is proofs, unfolding and re-folding of lists, necessary assertions, memory management enforced by the type system, etc. (Some might say I am somewhat lax in my handling of pointers, using the simplest type '''ptr''' instead of more elaborate types.)
 
<syntaxhighlight lang="ats">#include "share/atspre_staload.hats"
staload UN = "prelude/SATS/unsafe.sats"
 
(* For simplicity, I implement this task only for sorting values of
non-linear type. That would include all the basic integer types,
garbage-collected strings, etc.
Also I freely create arrays as workspace, although the size of any
workspace array is equal only to the number of indices (not to the
number of values). *)
 
extern fn {a : t@ype}
sort_disjoint_sublist$cmp : (a, a) -<> int
 
fn {a : t@ype}
sort_disjoint_sublist
{m : int}
{n : int}
(values : &list_vt (a, m) >> _,
indices : list ([i : nat | i < m] int i, n))
: void =
let
typedef index = [i : nat | i < m] int i
 
prval () = lemma_list_vt_param values
prval () = lemma_list_param indices
val num_values : size_t m = i2sz (list_vt_length values)
and num_indices : size_t n = i2sz (list_length indices)
 
(* Put the indices in ascending order. *)
val @(pf_ix, pfgc_ix | p_ix) =
array_ptr_alloc<index> num_indices
macdef ix = !p_ix
val () = array_initize_list<index> (ix, sz2i num_indices, indices)
implement
array_quicksort$cmp<index> (x, y) =
if x < y then ~1 else 1
val () = array_quicksort<index> (ix, num_indices)
 
(* Initialize a "refs" array with pointers to the relevant list
nodes. The pointers will be in ascending index order. *)
val @(pf_refs, pfgc_refs | p_refs) =
array_ptr_alloc<ptr> num_indices
fun
init_refs {j : nat | j <= m}
{i : nat | i <= n}
{p_refs : addr}
.<m - j>.
(pf_refs : !array_v (ptr?, p_refs + (i * sizeof ptr),
n - i)
>> array_v (ptr, p_refs + (i * sizeof ptr),
n - i) |
ix : &array (index, n),
p_refs : ptr p_refs,
i : size_t i,
values : &list_vt (a, m - j),
j : size_t j)
:<!wrt> void =
if i < num_indices then
case+ values of
| list_vt_nil () => $effmask_exn assertloc (false)
| @ list_vt_cons (head, tail) =>
if j = ix[i] then
let
prval @(pf_elem, pf_rest) = array_v_uncons pf_refs
val p = ptr_add<ptr> (p_refs, i)
val () = ptr_set<ptr> (pf_elem | p, addr@ values)
val () = init_refs (pf_rest | ix, p_refs, succ i,
tail, succ j)
prval () = pf_refs := array_v_cons (pf_elem, pf_rest)
prval () = fold@ values
in
end
else
let
val () = init_refs (pf_refs | ix, p_refs, i,
tail, succ j)
prval () = fold@ values
in
end
else
let
prval () = pf_refs := array_v_unnil_nil{ptr?, ptr} pf_refs
in
end
val () = init_refs (pf_refs | ix, p_refs, i2sz 0, values, i2sz 0)
 
(* Sort through the "refs" pointers. Here we will do that by
copying the values to an array, sorting the array, then writing
the sorted values back. One could also do the sort in place,
however. *)
val @(pf_vals, pfgc_vals | p_vals) =
array_ptr_alloc<a> num_indices
macdef vals = !p_vals
implement
array_initize$init<a> (i, x) =
let
val @(pf1, fpf1 | p1) = $UN.ptr_vtake{array (ptr, n)} p_refs
macdef refs = !p1
val i1 = g1ofg0 i
prval () = lemma_g1uint_param i1
val () = assertloc (i1 < num_indices)
val @(pf2, fpf2 | p2) = $UN.ptr_vtake{List1_vt a} (refs[i1])
val+ @ list_vt_cons (head, tail) = !p2
val () = x := head
prval () = fold@ (!p2)
prval () = fpf2 pf2
prval () = fpf1 pf1
in
end
val () = array_initize<a> (vals, num_indices)
implement
array_quicksort$cmp<a> (x, y) =
sort_disjoint_sublist$cmp<a> (x, y)
val () = array_quicksort<a> (vals, num_indices)
fun
write_back_values
{i : nat | i <= n}
{p_refs : addr}
(pf_refs : !array_v (ptr, p_refs, n) |
p_refs : ptr p_refs,
vals : &array (a, n),
i : size_t i)
: void =
if i <> num_indices then
let
macdef refs = !p_refs
val @(pf1, fpf1 | p1) = $UN.ptr_vtake{List1_vt a} (refs[i])
val+ @ list_vt_cons (head, tail) = !p1
val () = head := vals[i]
prval () = fold@ (!p1)
prval () = fpf1 pf1
in
write_back_values (pf_refs | p_refs, vals, succ i)
end
val () = write_back_values (pf_refs | p_refs, vals, i2sz 0)
in
array_ptr_free (pf_ix, pfgc_ix | p_ix);
array_ptr_free (pf_refs, pfgc_refs | p_refs);
array_ptr_free (pf_vals, pfgc_vals | p_vals)
end
 
implement
sort_disjoint_sublist$cmp<int> (x, y) =
if x < y then
~1
else if y < x then
1
else
0
 
implement
main0 () =
let
var values = $list_vt{int} (7, 6, 5, 4, 3, 2, 1, 0)
val indices = $list{[i : nat | i < 8] int i} (6, 1, 7)
in
println! values;
sort_disjoint_sublist<int> (values, indices);
println! values;
free values
end</syntaxhighlight>
 
{{out}}
<pre>$ patscc -DATS_MEMALLOC_GCBDW -O3 sort_disjoint_sublist_task.dats -lgc && ./a.out
7, 6, 5, 4, 3, 2, 1, 0
7, 0, 5, 4, 3, 2, 1, 6</pre>
 
=={{header|AutoHotkey}}==
<syntaxhighlight lang="autohotkey">Sort_disjoint_sublist(Values, Indices){
A := [], B:=[], C := [], D := []
for k, v in Indices
A[v] := 1 , B[Values[v]] := v
for k, v in A
C.Push(k)
for k, v in B
D.Push(k)
for k, v in D
Values[C[A_Index]] := D[A_Index]
return Values
}</syntaxhighlight>
Examples:<syntaxhighlight lang="autohotkey">Values := [7, 6, 5, 4, 3, 2, 1, 0]
Indices := [7, 2, 8]
Values := Sort_disjoint_sublist(Values, Indices)
for k, v in Values
output .= v ", "
MsgBox % "[" Trim(output, ", ") "]" ; show output</syntaxhighlight>
{{out}}
<pre>[7, 0, 5, 4, 3, 2, 1, 6]</pre>
 
=={{header|BASIC}}==
==={{header|Applesoft BASIC}}===
The [[#GW-BASIC|GW-BASIC]] solution works without any changes.
 
==={{header|BBC BASIC}}===
{{works with|BBC BASIC for Windows}}
<langsyntaxhighlight lang="bbcbasic"> INSTALL @lib$+"SORTLIB"
Sort% = FN_sortinit(0,0) : REM Ascending
Line 373 ⟶ 1,099:
o$ += STR$(l%(i%)) + ", "
NEXT
= LEFT$(LEFT$(o$)) + "]"</langsyntaxhighlight>
{{out}}
'''Output:'''
<pre>[7, 0, 5, 4, 3, 2, 1, 6]</pre>
<pre>
 
[7, 0, 5, 4, 3, 2, 1, 6]
==={{header|Chipmunk Basic}}===
</pre>
{{works with|Chipmunk Basic|3.6.4}}
The [[#GW-BASIC|GW-BASIC]] solution works without any changes.
<syntaxhighlight lang="qbasic">100 cls
110 dim values(7)
120 data 7,6,5,4,3,2,1,0
130 for i = 0 to 7
140 read values(i)
150 next
160 dim indices(2)
170 data 6,1,7
180 for i = 0 to 2
190 read indices(i)
200 next
210 print "Before sort:"
220 for i = 0 to ubound(values)
230 print values(i);
240 next i
250 print
260 print
270 print "After sort:"
280 for i = 0 to 1
290 if values(indices(i)) > values(indices(i+1)) then
300 temp = values(indices(i)) : values(indices(i)) = values(indices(i+1)) : values(indices(i+1)) = temp
310 endif
320 next i
330 for i = 0 to ubound(values)
340 print values(i);
350 next i
360 print
370 end</syntaxhighlight>
{{out}}
<pre>Same as FreeBASIC entry.</pre>
 
==={{header|FreeBASIC}}===
<syntaxhighlight lang="freebasic">dim as integer value(0 to 7) = {7, 6, 5, 4, 3, 2, 1, 0}
dim as integer index(0 to 2) = {6, 1, 7}, i
 
for i = 0 to 1
if value(index(i))>value(index(i+1)) then
swap value(index(i)), value(index(i+1))
end if
next i
 
for i = 0 to 7
print value(i);
next i : print</syntaxhighlight>
{{out}}<pre> 7 0 5 4 3 2 1 6</pre>
 
==={{header|GW-BASIC}}===
{{works with|Applesoft BASIC}}
{{works with|Chipmunk Basic}}
{{works with|PC-BASIC|any}}
{{works with|QBasic}}
{{works with|Quite BASIC}}
<syntaxhighlight lang="qbasic">100 CLS : rem 100 HOME for Applesoft BASIC
110 DIM V(7)
120 DATA 7,6,5,4,3,2,1,0
130 FOR C = 0 TO 7
140 READ V(C)
150 NEXT C
160 DIM I(2)
170 DATA 6,1,7
180 FOR C = 0 TO 2
190 READ I(C)
200 NEXT C
210 PRINT "Before sort:"
220 FOR C = 0 TO 7
230 PRINT V(C); " ";
240 NEXT C
250 PRINT
260 PRINT
270 PRINT "After sort:"
280 FOR C = 0 TO 1
290 IF V(I(C)) > V(I(C+1)) THEN LET T = V(I(C)) : LET V(I(C)) = V(I(C+1)) : LET V(I(C+1)) = T
300 NEXT C
310 FOR C = 0 TO 7
320 PRINT V(C); " ";
330 NEXT C
340 END</syntaxhighlight>
{{out}}
<pre>Same as FreeBASIC entry.</pre>
 
==={{header|Minimal BASIC}}===
{{works with|QBasic}}
{{works with|QuickBasic}}
{{works with|Applesoft BASIC}}
{{works with|BASICA}}
{{works with|Chipmunk Basic}}
{{works with|GW-BASIC}}
{{works with|MSX BASIC|any}}
<syntaxhighlight lang="qbasic">110 DIM V(7)
120 DATA 7,6,5,4,3,2,1,0
130 FOR C = 0 TO 7
140 READ V(C)
150 NEXT C
160 DIM I(2)
170 DATA 6,1,7
180 FOR C = 0 TO 2
190 READ I(C)
200 NEXT C
210 PRINT "BEFORE SORT:"
220 FOR C = 0 TO 7
230 PRINT V(C);" ";
240 NEXT C
250 PRINT
260 PRINT
270 PRINT "AFTER SORT:"
280 FOR C = 0 TO 1
290 IF V(I(C)) > V(I(C+1)) THEN 310
300 GOTO 340
310 LET T = V(I(C))
320 LET V(I(C)) = V(I(C+1))
330 LET V(I(C+1)) = T
340 NEXT C
350 FOR C = 0 TO 7
360 PRINT V(C);" ";
370 NEXT C
380 END</syntaxhighlight>
{{out}}
<pre>Same as FreeBASIC entry.</pre>
 
==={{header|MSX Basic}}===
{{works with|MSX BASIC|any}}
The [[#GW-BASIC|GW-BASIC]] solution works without any changes.
 
==={{header|PureBasic}}===
Based on the C implementation
<syntaxhighlight lang="purebasic">Procedure Bubble_sort(Array idx(1), n, Array buf(1))
Protected i, j
SortArray(idx(),#PB_Sort_Ascending)
For i=0 To n
For j=i+1 To n
If buf(idx(j)) < buf(idx(i))
Swap buf(idx(j)), buf(idx(i))
EndIf
Next
Next
EndProcedure
 
Procedure main()
DataSection
values: Data.i 7, 6, 5, 4, 3, 2, 1, 0
indices:Data.i 6, 1, 7
EndDataSection
Dim values.i(7) :CopyMemory(?values, @values(), SizeOf(Integer)*8)
Dim indices.i(2):CopyMemory(?indices,@indices(),SizeOf(Integer)*3)
If OpenConsole()
Protected i
PrintN("Before sort:")
For i=0 To ArraySize(values())
Print(Str(values(i))+" ")
Next
PrintN(#CRLF$+#CRLF$+"After sort:")
Bubble_sort(indices(), ArraySize(indices()), values())
For i=0 To ArraySize(values())
Print(Str(values(i))+" ")
Next
Print(#CRLF$+#CRLF$+"Press ENTER to exit")
Input()
EndIf
EndProcedure
 
main()</syntaxhighlight>
{{out}}
<pre>Before sort:
7 6 5 4 3 2 1 0
 
After sort:
7 0 5 4 3 2 1 6</pre>
 
==={{header|Run BASIC}}===
Normally we sort with SQLite in memory. Faster and less code
<syntaxhighlight lang="runbasic">sortData$ = "7, 6, 5, 4, 3, 2, 1, 0"
sortIdx$ = "7, 2, 8"
 
numSort = 8
dim sortData(numSort)
for i = 1 to numSort
sortData(i) = val(word$(sortData$,i,","))
next i
 
while word$(sortIdx$,s + 1) <> ""
s = s + 1
idx = val(word$(sortIdx$,s))
gosub [bubbleSort]
wend
end
 
[bubbleSort]
sortSw = 1
while sortSw = 1
sortSw = 0
for i = idx to numSort - 1 ' start sorting at idx
if sortData(i) > sortData(i+1) then
sortSw = 1
sortHold = sortData(i)
sortData(i) = sortData(i+1)
sortData(i+1) = sortHold
end if
next i
wend
RETURN</syntaxhighlight>
 
==={{header|True BASIC}}===
<syntaxhighlight lang="qbasic">OPTION BASE 0
 
SUB SWAP(vb1, vb2)
LET temp = vb1
LET vb1 = vb2
LET vb2 = temp
END SUB
 
DIM values(7)
DATA 7, 6, 5, 4, 3, 2, 1, 0
FOR i = 0 TO 7
READ values(i)
NEXT i
DIM indices(2)
DATA 6, 1, 7
FOR i = 0 TO 2
READ indices(i)
NEXT i
PRINT "Before sort:"
FOR i = 0 TO 7 !UBOUND(values)
PRINT values(i);
NEXT i
PRINT
PRINT
PRINT "After sort:"
FOR i = 0 TO 1
IF values(indices(i)) > values(indices(i+1)) THEN CALL SWAP (values(indices(i)), values(indices(i+1)))
NEXT i
FOR i = 0 TO 7 !UBOUND(values)
PRINT values(i);
NEXT i
 
END</syntaxhighlight>
{{out}}
<pre>Same as BASIC entry.</pre>
 
==={{header|Yabasic}}===
<syntaxhighlight lang="vb">dim values(7)
values(0) = 7 : values(1) = 6 : values(2) = 5
values(3) = 4 : values(4) = 3 : values(5) = 2
values(6) = 1 : values(7) = 0
 
dim indices(2)
indices(0) = 6 : indices(1) = 1 : indices(2) = 7
 
print "Before sort:"
for i = 0 to arraysize(values(),1)
print values(i), " ";
next i
 
print "\n\nAfter sort:"
for i = 0 to 1
if values(indices(i)) > values(indices(i + 1)) then
temp = values(indices(i)) : values(indices(i)) = values(indices(i+1)) : values(indices(i+1)) = temp
end if
next i
for i = 0 to arraysize(values(),1)
print values(i), " ";
next i
end</syntaxhighlight>
{{out}}
<pre>Same as BASIC entry.</pre>
 
=={{header|Bracmat}}==
<langsyntaxhighlight lang="bracmat">7 6 5 4 3 2 1 0:?values
& 6 1 7:?indices
& 0:?sortedValues:?sortedIndices
Line 395 ⟶ 1,391:
& !A !value !Z:?values
)
& out$!values;</langsyntaxhighlight>
{{out}}
Output:
<pre>7 0 5 4 3 2 1 6</pre>
 
=={{header|C}}==
<langsyntaxhighlight Clang="c">#include <stdio.h>
 
/* yes, bubble sort */
Line 432 ⟶ 1,428:
 
return 0;
}</langsyntaxhighlight>
 
=={{header|C sharp}}==
<langsyntaxhighlight lang="csharp">using System;
using System.Linq;
using System.Collections.Generic;
Line 463 ⟶ 1,459:
}
}</langsyntaxhighlight>
 
=={{header|C++}}==
<langsyntaxhighlight lang="cpp">#include <algorithm>
#include <iostream>
#include <iterator>
Line 499 ⟶ 1,495:
 
return 0;
}</langsyntaxhighlight>
{{out}}
<pre>
Line 507 ⟶ 1,503:
{{trans|Go}}
Solution that sorts using a custom iterator that iterates a disjoint sublist.
<langsyntaxhighlight lang="cpp">#include <algorithm>
#include <iostream>
#include <iterator>
Line 568 ⟶ 1,564:
 
return 0;
}</langsyntaxhighlight>
{{out}}
<pre>
Line 575 ⟶ 1,571:
 
=={{header|Clojure}}==
<langsyntaxhighlight lang="clojure">(defn disjoint-sort [coll idxs]
(let [val-subset (keep-indexed #(when ((set idxs) %) %2) coll)
replacements (zipmap (set idxs) (sort val-subset))]
(apply assoc coll (flatten (seq replacements)))))</langsyntaxhighlight>
 
{{out}}
Line 585 ⟶ 1,581:
 
=={{header|Common Lisp}}==
<langsyntaxhighlight lang="lisp">(defun disjoint-sort (values indices)
"Destructively perform a disjoin sublist sort on VALUES with INDICES."
(loop :for element :in
Line 593 ⟶ 1,589:
:for index :across (sort indices '<)
:do (setf (svref values index) element))
values)</langsyntaxhighlight>
{{out}}
<pre>CL-USER> (disjoint-sort #(7 6 5 4 3 2 1 0) #(6 1 7))
Line 599 ⟶ 1,595:
 
=={{header|D}}==
<langsyntaxhighlight lang="d">import std.algorithm, std.range, std.array;
 
void main() {
Line 608 ⟶ 1,604:
 
assert(data == [7, 0, 5, 4, 3, 2, 1, 6]);
}</langsyntaxhighlight>
===Lower Level version===
<langsyntaxhighlight lang="d">import std.algorithm: swap;
 
void disjointSort(T, U)(T[] arr, U[] indexes)
Line 650 ⟶ 1,646:
disjointSort(data, indexes);
assert(data == [7.0, 0.0, 5.0, 4.0, 3.0, 2.0, 1.0, 6.0]);
}</langsyntaxhighlight>
 
===Simple Alternative Version===
<langsyntaxhighlight lang="d">import std.stdio, std.algorithm;
 
void main() {
Line 671 ⟶ 1,667:
 
assert(data == [7.0, 0.0, 5.0, 4.0, 3.0, 2.0, 1.0, 6.0]);
}</langsyntaxhighlight>
 
=={{header|Delphi}}==
{{works with|Delphi|6.0}}
{{libheader|SysUtils,StdCtrls}}
<syntaxhighlight lang="Delphi">{Test values}
 
var Values: array [0..7] of integer = (7, 6, 5, 4, 3, 2, 1, 0);
var indices: array [0..2] of integer = (6, 1, 7);
 
function CompareValues(Item1, Item2: Pointer): Integer;
{Compare the values pointed to by the indices}
begin
Result:=Values[integer(Item1)]-Values[integer(Item2)];
end;
 
function CompareIndices(Item1, Item2: Pointer): Integer;
{Compare the indices themselves}
begin
Result:=integer(Item1)-integer(Item2);
end;
 
procedure SortDisjointSublist(Memo: TMemo);
var L1,L2: TList;
var I,Inx1,Inx2: integer;
var OutList: TIntegerDynArray;
var S: string;
begin
L1:=TList.Create;
L2:=TList.Create;
try
{Copy values array to output array}
SetLength(OutList,Length(Values));
for I:=0 to High(Values) do OutList[I]:=Values[I];
{Load two lists with the indices}
for I:=0 to High(Indices) do
begin
L1.Add(Pointer(Indices[I]));
L2.Add(Pointer(Indices[I]));
end;
{Sort by index and by value}
L1.Sort(CompareValues);
L2.Sort(CompareIndices);
{Copy the sorted values through the sorted indices}
for I:=0 to L1.Count-1 do
OutList[Integer(L2[I])]:=Values[Integer(L1[I])];
{Display the result}
S:='[';
for I:=0 to High(OutLIst) do
begin
if I>0 then S:=S+' ';
S:=S+IntToStr(OutList[I]);
end;
S:=S+']';
Memo.Lines.Add(S);
finally
L1.Free;
L2.Free;
end;
end;</syntaxhighlight>
{{out}}<pre>
[7 0 5 4 3 2 1 6]
Elapsed Time: 0.626 ms.</pre>
 
=={{header|EasyLang}}==
<syntaxhighlight>
val[] = [ 7 6 5 4 3 2 1 0 ]
ind[] = [ 7 2 8 ]
#
for i = 1 to len ind[] - 1
for j = i + 1 to len ind[]
if ind[j] < ind[i]
swap ind[j] ind[i]
.
.
.
for i = 1 to len ind[] - 1
for j = i + 1 to len ind[]
if val[ind[j]] < val[ind[i]]
swap val[ind[j]] val[ind[i]]
.
.
.
print val[]
</syntaxhighlight>
 
=={{header|EchoLisp}}==
<langsyntaxhighlight lang="scheme">
(define (sort-disjoint values indices)
(define sorted (list-sort <
Line 691 ⟶ 1,771:
(task)
→ (7 0 5 4 3 2 1 6)
</syntaxhighlight>
</lang>
 
=={{header|Elena}}==
ELENA 56.0x :
<langsyntaxhighlight lang="elena">import extensions;
import system'routines;
import system'culture;
Line 703 ⟶ 1,783:
sortSublist(indices)
{
var subList := indices.orderBy::(x => x)
.zipBy(indices.selectBy::(i => self[i])
.orderBy::(x => x), (index,val => new{ Index = index; Value = val; }))
.toArray();
var list := self.clone();
subList.forEach::(r)
{
list[r.Index] := r.Value
Line 723 ⟶ 1,803:
console.printLine(list.sortSublist(new int[]{6, 1, 7}).asEnumerable())
}</langsyntaxhighlight>
{{out}}
<pre>7,0,5,4,3,2,1,6</pre>
<pre>
7,0,5,4,3,2,1,6
</pre>
 
=={{header|Elixir}}==
<langsyntaxhighlight lang="elixir">defmodule Sort_disjoint do
def sublist(values, indices) when is_list(values) and is_list(indices) do
indices2 = Enum.sort(indices)
Line 748 ⟶ 1,826:
values = [7, 6, 5, 4, 3, 2, 1, 0]
indices = [6, 1, 7]
IO.inspect Sort_disjoint.sublist(values, indices)</langsyntaxhighlight>
 
{{out}}
<pre>[7, 0, 5, 4, 3, 2, 1, 6]</pre>
<pre>
[7, 0, 5, 4, 3, 2, 1, 6]
</pre>
 
=={{header|Erlang}}==
<syntaxhighlight lang="erlang">
<lang Erlang>
-module( sort_disjoint ).
 
Line 778 ⟶ 1,853:
merge( Index, {[_H | Values], [{Index, Value} | Sorted_indices_values]} ) -> {Value, {Values, Sorted_indices_values}};
merge( _Index, {[H | Values], Sorted_indices_values} ) -> {H, {Values, Sorted_indices_values}}.
</syntaxhighlight>
</lang>
{{out}}
<pre>20> sort_disjoint:task().
<pre>
[7,0,5,4,3,2,1,6]</pre>
20> sort_disjoint:task().
[7,0,5,4,3,2,1,6]
</pre>
 
=={{header|ERRE}}==
<langsyntaxhighlight ERRElang="erre">PROGRAM DISJOINT
 
DIM LST%[7],INDICES%[2]
Line 833 ⟶ 1,906:
ShowList(LST%[]->O$)
PRINT(O$)
END PROGRAM</langsyntaxhighlight>
{{out}}
<pre>[ 7, 0, 5, 4, 3, 2, 1, 6]</pre>
<pre>
[ 7, 0, 5, 4, 3, 2, 1, 6]
</pre>
 
=={{header|Euphoria}}==
<langsyntaxhighlight lang="euphoria">include sort.e
 
function uniq(sequence s)
Line 868 ⟶ 1,939:
 
constant data = {7, 6, 5, 4, 3, 2, 1, 0}
constant indexes = {7, 2, 8}</langsyntaxhighlight>
{{out}}
 
pre>{7,0,5,4,3,2,1,6}</pre>
Output:
<pre>{7,0,5,4,3,2,1,6}
</pre>
 
=={{header|F_Sharp|F#}}==
{{trans|Python}}
Works with arrays instead of lists because this algorithm is more efficient with a random access collection type. Returns a copy of the array, as is usually preferred in F#.
<langsyntaxhighlight lang="fsharp">let sortDisjointSubarray data indices =
let indices = Set.toArray indices // creates a sorted array
let result = Array.copy data
Line 886 ⟶ 1,955:
 
 
printfn "%A" (sortDisjointSubarray [|7;6;5;4;3;2;1;0|] (set [6;1;7]))</langsyntaxhighlight>
 
=={{header|Factor}}==
<langsyntaxhighlight lang="factor">: disjoint-sort! ( values indices -- values' )
over <enumerated> nths unzip swap [ natural-sort ] bi@
pick [ set-nth ] curry 2each ;</langsyntaxhighlight>
{{out}}
<langsyntaxhighlight lang="factor">IN: scratchpad { 7 6 5 4 3 2 1 0 } { 6 1 7 } disjoint-sort! .
{ 7 0 5 4 3 2 1 6 }</langsyntaxhighlight>
 
=={{header|Fortran}}==
{{works with|Fortran|90 and later}}
<langsyntaxhighlight lang="fortran">program Example
implicit none
 
Line 933 ⟶ 2,002:
end subroutine Isort
end program Example</langsyntaxhighlight>
{{out}}
Output
<pre> 7 0 5 4 3 2 1 6</pre>
 
=={{header|Go}}==
<langsyntaxhighlight lang="go">package main
 
import (
Line 974 ⟶ 2,043:
}
fmt.Println("sorted: ", values)
}</langsyntaxhighlight>
{{out}}
Output:
<pre>initial: [7 6 5 4 3 2 1 0]
<pre>
initialsorted: [7 60 5 4 3 2 1 06]</pre>
sorted: [7 0 5 4 3 2 1 6]
</pre>
Alternative algorithm, sorting in place through the extra level of indirection.
 
Compared to the strategy of extract-sort-replace, this strategy avoids the space overhead of the work area and the time overhead of extracting and reinserting elements. At some point however, the cost of indirection multiplied by O(log n) would dominate, and extract-sort-replace would become preferable.
<langsyntaxhighlight lang="go">package main
 
import (
Line 1,039 ⟶ 2,106:
sort.Sort(s)
fmt.Println("sorted: ", s.values)
}</langsyntaxhighlight>
 
=={{header|Groovy}}==
Groovy allows List-valued indexing to "gather" and "scatter" arbitrary sublists, making the solution almost trivial.
<langsyntaxhighlight lang="groovy">def sparseSort = { a, indices = ([] + (0..<(a.size()))) ->
indices.sort().unique()
a[indices] = a[indices].sort()
a
}</langsyntaxhighlight>
 
Test:
<langsyntaxhighlight lang="groovy">def a = [7, 6, 5, 4, 3, 2, 1, 0]
 
println a
Line 1,058 ⟶ 2,125:
println a
println sparseSort(a) // default == sort all
println a</langsyntaxhighlight>
 
Output:
Line 1,072 ⟶ 2,139:
Here are three variations on the solution: using ordinary lists, immutable "boxed" arrays, and mutable "unboxed" arrays.
 
<langsyntaxhighlight lang="haskell">import Control.Monad
import qualified Data.Array as A
import Data.Array.IArray
Line 1,117 ⟶ 2,184:
print $ disSort1 xs is
print $ disSort2 xs is
print $ disSort3 xs is</langsyntaxhighlight>
 
 
Or, in terms of Data.Map:
<langsyntaxhighlight lang="haskell">import Data.Map as M (fromList, keys, lookup)
import Control.Applicative ((<|>))
import Data.Maybe (mapMaybe)
Line 1,136 ⟶ 2,203:
 
main :: IO ()
main = print $ disjointSort [6, 1, 7] [7, 6, 5, 4, 3, 2, 1, 0]</langsyntaxhighlight>
{{Out}}
<pre>[7,0,5,4,3,2,1,6]</pre>
 
=={{header|Icon}} and {{header|Unicon}}==
 
Icon's lists are 1-based, so the example uses (7, 2, 8) as the indices, not (6, 1 7).
 
<syntaxhighlight lang="icon">link sort # get the 'isort' procedure for sorting a list
<lang icon>
link sort # get the 'isort' procedure for sorting a list
 
procedure sortDisjoint (items, indices)
Line 1,169 ⟶ 2,234:
every writes (!result || " ")
write ()
end</syntaxhighlight>
end
{{out}}<pre>7 6 5 4 3 2 1 0
</lang>
 
Output:
<pre>
7 6 5 4 3 2 1 0
2 7 8
7 0 5 4 3 2 1 6</pre>
</pre>
 
The expression <code>!indices</code> generates the value of each index in turn, so the line <langsyntaxhighlight lang="icon">every put (values, result[!indices])</langsyntaxhighlight> effectively loops through each index, putting <code>result[index]</code> into the list 'values'.
 
=={{header|Io}}==
Io does not come with a set type.
<langsyntaxhighlight Iolang="io">List disjointSort := method(indices,
sortedIndices := indices unique sortInPlace
sortedValues := sortedIndices map(idx,at(idx)) sortInPlace
Line 1,190 ⟶ 2,250:
)
 
list(7,6,5,4,3,2,1,0) disjointSort(list(6,1,7)) println</langsyntaxhighlight>
{{output}}
<pre>list(7, 0, 5, 4, 3, 2, 1, 6)</pre>
Line 1,197 ⟶ 2,257:
Note that the task requires us to ignore the order of the indices.
 
<langsyntaxhighlight lang="j"> 7 6 5 4 3 2 1 0 (/:~@:{`[`]}~ /:~@~.) 6 1 7
7 0 5 4 3 2 1 6</langsyntaxhighlight>
 
Compare this with:
<langsyntaxhighlight lang="j"> 6 1 7 /:~@:{`[`]} 7 6 5 4 3 2 1 0
7 1 5 4 3 2 0 6</langsyntaxhighlight>
 
Here, the order of the indices specifies the order we want the selected items to be sorted in: 7 '''''1''''' 5 4 3 2 '''''0 6'''''
Line 1,209 ⟶ 2,269:
{{works with|Java|1.5+}}
This function will modify the index array and the values list.
<langsyntaxhighlight lang="java5">import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
Line 1,236 ⟶ 2,296:
System.out.println(list);
}
}</langsyntaxhighlight>
{{out}}
<pre>[7, 6, 5, 4, 3, 2, 1, 0]
Line 1,244 ⟶ 2,304:
{{trans|Go}}
Shorter solution that sorts a list "wrapper" which represents a "view" into the disjoint sublist of the list.
<langsyntaxhighlight lang="java5">import java.util.Arrays;
import java.util.Collections;
import java.util.List;
Line 1,267 ⟶ 2,327:
System.out.println(list);
}
}</langsyntaxhighlight>
{{out}}
<pre>[7, 6, 5, 4, 3, 2, 1, 0]
Line 1,275 ⟶ 2,335:
===ES5===
====Iterative====
 
Does not check for duplicate indices.
<langsyntaxhighlight JavaScriptlang="javascript">function sort_disjoint(values, indices) {
var sublist = [];
indices.sort(function(a, b) { return a > b; });
Line 1,292 ⟶ 2,351:
 
return values;
}</langsyntaxhighlight>
 
====Functional====
<syntaxhighlight lang="javascript">(function () {
 
<lang JavaScript>(function () {
'use strict';
 
Line 1,322 ⟶ 2,380:
return disjointSort([7, 6, 5, 4, 3, 2, 1, 0], [6, 1, 7])
 
})();</langsyntaxhighlight>
 
{{Out}}
<pre>[7, 0, 5, 4, 3, 2, 1, 6]</pre>
 
===ES6===
<syntaxhighlight lang="javascript">(() => {
 
<lang JavaScript>(() => {
'use strict';
 
Line 1,426 ⟶ 2,482:
// MAIN ---
return main();
})();</langsyntaxhighlight>
{{Out}}
<pre>[7, 0, 5, 4, 3, 2, 1, 6]</pre>
 
=={{header|jq}}==
 
We define a jq function, disjointSort, that accepts the array of values as input,
but for clarity we first define a utility function for updating an array at multiple places:
<langsyntaxhighlight lang="jq">def setpaths(indices; values):
reduce range(0; indices|length) as $i
(.; .[indices[$i]] = values[$i]);
Line 1,442 ⟶ 2,497:
# Set $sorted to the sorted array of values at $ix:
| ([ .[ $ix[] ] ] | sort) as $sorted
| setpaths( $ix; $sorted) ;</langsyntaxhighlight>
Example:<langsyntaxhighlight lang="jq">
[7, 6, 5, 4, 3, 2, 1, 0] | disjointSort( [6, 1, 7] )</langsyntaxhighlight>produces:
[7,0,5,4,3,2,1,6]
 
=={{header|Julia}}==
{{works with|Julia|0.6}}
<syntaxhighlight lang="julia">function sortselected(a::AbstractVector{<:Real}, s::AbstractVector{<:Integer})
 
<lang julia>function sortselected(a::AbstractVector{<:Real}, s::AbstractVector{<:Integer})
sel = unique(sort(s))
if sel[1] < 1 || length(a) < sel[end]
Line 1,464 ⟶ 2,518:
b = sortselected(a, sel)
 
println("Original: $a\n\tsorted on $sel\n -> sorted array: $b")</langsyntaxhighlight>
 
{{out}}
<pre>Original: [7, 6, 5, 4, 3, 2, 1, 0]
Line 1,472 ⟶ 2,525:
 
=={{header|K}}==
<syntaxhighlight lang="k">
<lang K>
{@[x;y@<y;:;a@<a:x@y]}[7 6 5 4 3 2 1 0;6 1 7]
7 0 5 4 3 2 1 6
</syntaxhighlight>
</lang>
 
===Another way===
<syntaxhighlight lang="k">sort : {x[<x]}
<lang K>
sort : {x[<x]}
nums : 7 6 5 4 3 2 1 0
i : sort 6 1 7
nums[i] : sort nums[i]
nums
7 0 5 4 3 2 1 6</syntaxhighlight>
</lang>
 
=={{header|Kotlin}}==
<langsyntaxhighlight lang="scala">// version 1.1.51
 
/* in place sort */
Line 1,504 ⟶ 2,555:
values.sortDisjoint(indices)
println("Sorted array : ${values.asList()}")
}</syntaxhighlight>
}
</lang>
 
{{out}}
<pre>Original array : [7, 6, 5, 4, 3, 2, 1, 0] sorted on indices [6, 1, 7]
<pre>
OriginalSorted array : [7, 60, 5, 4, 3, 2, 1, 0] sorted on indices [6, 1, 7]</pre>
 
Sorted array : [7, 0, 5, 4, 3, 2, 1, 6]
=={{header|Ksh}}==
</pre>
<syntaxhighlight lang="ksh">
#!/bin/ksh
 
# Sort disjoint sublist
 
# # Variables:
#
typeset -a arr_Val=( 7 6 5 4 3 2 1 0 )
typeset -a arr_Ind=( 6 1 7 )
integer i
 
# # Functions:
#
# # Function _insertionSort(array) - Insertion sort of array of integers
#
function _insertionSort {
typeset _arr ; nameref _arr="$1"
typeset _i _j _val ; integer _i _j _val
 
for (( _i=1; _i<${#_arr[*]}; _i++ )); do
_val=${_arr[_i]}
(( _j = _i - 1 ))
while (( _j>=0 && _arr[_j]>_val )); do
_arr[_j+1]=${_arr[_j]}
(( _j-- ))
done
_arr[_j+1]=${_val}
done
}
 
######
# main #
######
print "Before sort: ${arr_Val[*]}"
 
typeset -a arr_2sort
for ((i=0; i<${#arr_Ind[*]}; i++)); do
arr_2sort+=( ${arr_Val[${arr_Ind[i]}]} )
done
 
_insertionSort arr_2sort # Sort the chosen values
_insertionSort arr_Ind # Sort the indices
 
for ((i=0; i<${#arr_Ind[*]}; i++)); do
arr_Val[${arr_Ind[i]}]=${arr_2sort[i]}
done
 
print "After sort: ${arr_Val[*]}"</syntaxhighlight>
{{out}}<pre>
Before sort: 7 6 5 4 3 2 1 0
After sort: 7 0 5 4 3 2 1 6</pre>
 
=={{header|Lua}}==
<langsyntaxhighlight lang="lua">values = { 7, 6, 5, 4, 3, 2, 1, 0 }
indices = { 6, 1, 7 }
 
Line 1,547 ⟶ 2,647:
for i = 1, #values do
io.write( values[i], " " )
end</langsyntaxhighlight>
{{out}}
<pre>7 0 5 4 3 2 1 6</pre>
 
=={{header|Maple}}==
<langsyntaxhighlight Maplelang="maple">sortDisjoint := proc(values, indices::set)
local vals,inds,i:
vals := sort([seq(values[i], i in indices)]):
Line 1,560 ⟶ 2,661:
end proc:
tst := Array([7,6,5,4,3,2,1,0]):
sortDisjoint(tst,{7,2,8});</langsyntaxhighlight>
{{out}}
<pre>[7 0 5 4 3 2 1 6]</pre>
 
=={{header|Mathematica}}/{{header|Wolfram Language}}==
<langsyntaxhighlight Mathematicalang="mathematica">Values = { 7, 6, 5, 4, 3, 2, 1, 0} ; Indices = { 7, 2, 8 };
Values[[Sort[Indices]]] = Sort[Values[[Indices]]];
Values</syntaxhighlight>
{{out}}
<pre>{ 7, 0, 5, 4, 3, 2, 1, 6 }</pre>
 
=={{header|MiniScript}}==
Values
<syntaxhighlight lang="miniscript">
-> { 7, 0, 5, 4, 3, 2, 1, 6 }</lang>
sortDisjointSublist = function(arr, indexes)
indexes.sort
newArr = arr[:]
sublist = []
for i in indexes
sublist.push(arr[i])
end for
sublist.sort
for i in range(0, indexes.len - 1)
arrIx = indexes[i]
newArr[arrIx] = sublist[i]
end for
return newArr
end function
 
print sortDisjointSublist([7,6,5,4,3,2,1,0], [6,1,7])
</syntaxhighlight>
{{out}}
<pre>
[7, 0, 5, 4, 3, 2, 1, 6]
</pre>
 
=={{header|NetRexx}}==
<langsyntaxhighlight NetRexxlang="netrexx">/* NetRexx */
options replace format comments java crossref symbols nobinary
 
Line 1,615 ⟶ 2,740:
say 'Idx:' iList.space
return
</syntaxhighlight>
</lang>
{{out}}
<pre>In: 7 6 5 4 3 2 1 0
<pre>
In: 7 6 5 4 3 2 1 0
Out: 7 0 5 4 3 2 1 6
Idx: 7 2 8</pre>
</pre>
 
=={{header|Nial}}==
 
{{works with|Q'Nial Version 6.3}}
<syntaxhighlight lang="nial">
 
<lang Nial>
values := [7, 6, 5, 4, 3, 2, 1, 0]
indices := sortup [6, 1, 7]
values#indices := sortup values#indices
7 0 5 4 3 2 1 6
</syntaxhighlight>
</lang>
 
=={{header|Nim}}==
<langsyntaxhighlight lang="nim">import algorithm
 
proc sortDisjoinSublist[T](data: var seq[T], indices: seq[int]) =
Line 1,649 ⟶ 2,770:
var d = @[7, 6, 5, 4, 3, 2, 1, 0]
sortDisjoinSublist(d, @[6, 1, 7])
echo d</langsyntaxhighlight>
{{out}}
Output:
<pre>@[7, 0, 5, 4, 3, 2, 1, 6]</pre>
 
Line 1,656 ⟶ 2,777:
{{trans|Go}}
Sorts an array "wrapper" which represents a "view" into the disjoint sublist of the array.
<langsyntaxhighlight lang="objc">#import <Foundation/Foundation.h>
 
@interface DisjointSublistView : NSMutableArray {
Line 1,706 ⟶ 2,827:
}
return 0;
}</langsyntaxhighlight>
{{out}}
<pre>(
Line 1,720 ⟶ 2,841:
 
=={{header|OCaml}}==
===With arrays:===
 
<syntaxhighlight lang="ocaml">let disjoint_sort cmp values indices =
With arrays:
 
<lang ocaml>let disjoint_sort cmp values indices =
let temp = Array.map (Array.get values) indices in
Array.sort cmp temp;
Line 1,734 ⟶ 2,853:
disjoint_sort compare values indices;
Array.iter (Printf.printf " %d") values;
print_newline()</langsyntaxhighlight>
 
With lists:
 
===With lists:===
<lang ocaml>let disjoint_sort cmp values indices =
<syntaxhighlight lang="ocaml">let disjoint_sort cmp values indices =
let indices = List.sort compare indices in
let rec aux acc j = function
Line 1,768 ⟶ 2,886:
let res = disjoint_sort compare values indices in
List.iter (Printf.printf " %d") res;
print_newline()</langsyntaxhighlight>
 
=={{header|ooRexx}}==
<langsyntaxhighlight ooRexxlang="oorexx">data = .array~of(7, 6, 5, 4, 3, 2, 1, 0)
-- this could be a list, array, or queue as well because of polymorphism
-- also, ooRexx arrays are 1-based, so using the alternate index set for the
Line 1,807 ⟶ 2,925:
-- the two and returning the sign, we give the expected
-- results for the compares
return (left - right)~sign</langsyntaxhighlight>
{{out}}
<pre>Sorted data is: [7, 0, 5, 4, 3, 2, 1, 6]</pre>
 
=={{header|Order}}==
<langsyntaxhighlight lang="c">#include <order/interpreter.h>
 
#define ORDER_PP_DEF_8sort_disjoint_sublist ORDER_PP_FN( \
Line 1,830 ⟶ 2,948:
ORDER_PP(
8sort_disjoint_sublist(8seq(7, 6, 5, 4, 3, 2, 1, 0), 8tuple(6, 1, 7))
)</langsyntaxhighlight>
 
=={{header|PARI/GP}}==
<langsyntaxhighlight lang="parigp">sortsome(v,which)={
my(x=sum(i=1,#which,1<<(which[i]-1)),u=vecextract(v,x));
u=vecsort(u);
Line 1,839 ⟶ 2,957:
for(i=1,#which,v[which[i]]=u[i]);
v
};</langsyntaxhighlight>
 
=={{header|pascal}}==
Tested free pascal.
<syntaxhighlight lang="pascal">
 
program disjointsort;
 
procedure swap(var a, b: Integer);
var
temp: Integer;
begin
temp := a;
a := b;
b := temp;
end;
 
procedure d_sort(var index,arr:array of integer);
var
n,i,j,num:integer;
begin
num:=length(index);
for n:=1 to 2 do
begin
for i:=0 to num-1 do
begin
for j:=i+1 to num-1 do
begin
if n=1 then if index[j]<index[i] then swap(index[j],index[i]);
if n=2 then if arr[index[j]]<arr[index[i]] then swap(arr[index[j]],arr[index[i]]);
end;
end;
end;
end;
 
var
i:integer;
arr :array[0 .. 7] of integer =(7, 6, 5, 4, 3, 2, 1, 0);
index:array[0 .. 2] of integer =(6, 1, 7);
 
 
begin
writeln('Before');
for i:=0 to 7 do write(arr[i],' ');
writeln;
d_sort(index,arr);
writeln('After');
for i:=0 to 7 do write(arr[i],' ');
writeln;
readln;
end.
</syntaxhighlight>
<pre>Before
7 6 5 4 3 2 1 0
After
7 0 5 4 3 2 1 6</pre>
 
=={{header|Perl}}==
<langsyntaxhighlight Perllang="perl">#!/usr/bin/perl -w
use strict ;
 
Line 1,855 ⟶ 3,028:
my @indices = ( 6 , 1 , 7 ) ;
disjointSort( \@values , @indices ) ;
print "[@values]\n" ;</langsyntaxhighlight>
{{out}}
Output:
<pre>[7 0 5 4 3 2 1 6]</pre>
 
=={{header|Phix}}==
<!--<syntaxhighlight lang="phix">(phixonline)-->
<lang Phix>function disjoint_sort(sequence s, sequence idx)
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
idx = unique(idx)
<span style="color: #008080;">function</span> <span style="color: #000000;">disjoint_sort</span><span style="color: #0000FF;">(</span><span style="color: #004080;">sequence</span> <span style="color: #000000;">s</span><span style="color: #0000FF;">,</span> <span style="color: #004080;">sequence</span> <span style="color: #000000;">idx</span><span style="color: #0000FF;">)</span>
integer l = length(idx)
<span style="color: #000000;">idx</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">unique</span><span style="color: #0000FF;">(</span><span style="color: #000000;">idx</span><span style="color: #0000FF;">)</span>
sequence copies = repeat(0, l)
<span style="color: #004080;">integer</span> <span style="color: #000000;">l</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">idx</span><span style="color: #0000FF;">)</span>
for i=1 to l do
<span style="color: #004080;">sequence</span> <span style="color: #000000;">copies</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">repeat</span><span style="color: #0000FF;">(</span><span style="color: #000000;">0</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">l</span><span style="color: #0000FF;">)</span>
copies[i] = s[idx[i]]
<span style="color: #008080;">for</span> <span style="color: #000000;">i</span><span style="color: #0000FF;">=</span><span style="color: #000000;">1</span> <span style="color: #008080;">to</span> <span style="color: #000000;">l</span> <span style="color: #008080;">do</span>
end for
<span style="color: #000000;">copies</span><span style="color: #0000FF;">[</span><span style="color: #000000;">i</span><span style="color: #0000FF;">]</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">s</span><span style="color: #0000FF;">[</span><span style="color: #000000;">idx</span><span style="color: #0000FF;">[</span><span style="color: #000000;">i</span><span style="color: #0000FF;">]]</span>
copies = sort(copies)
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
for i=1 to l do
<span style="color: #000000;">copies</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">sort</span><span style="color: #0000FF;">(</span><span style="color: #000000;">copies</span><span style="color: #0000FF;">)</span>
s[idx[i]] = copies[i]
<span style="color: #008080;">for</span> <span style="color: #000000;">i</span><span style="color: #0000FF;">=</span><span style="color: #000000;">1</span> <span style="color: #008080;">to</span> <span style="color: #000000;">l</span> <span style="color: #008080;">do</span>
end for
<span style="color: #000000;">s</span><span style="color: #0000FF;">[</span><span style="color: #000000;">idx</span><span style="color: #0000FF;">[</span><span style="color: #000000;">i</span><span style="color: #0000FF;">]]</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">copies</span><span style="color: #0000FF;">[</span><span style="color: #000000;">i</span><span style="color: #0000FF;">]</span>
return s
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
end function
<span style="color: #008080;">return</span> <span style="color: #000000;">s</span>
 
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
?disjoint_sort({7,6,5,4,3,2,1,0},{7,2,8})</lang>
<span style="color: #0000FF;">?</span><span style="color: #000000;">disjoint_sort</span><span style="color: #0000FF;">({</span><span style="color: #000000;">7</span><span style="color: #0000FF;">,</span><span style="color: #000000;">6</span><span style="color: #0000FF;">,</span><span style="color: #000000;">5</span><span style="color: #0000FF;">,</span><span style="color: #000000;">4</span><span style="color: #0000FF;">,</span><span style="color: #000000;">3</span><span style="color: #0000FF;">,</span><span style="color: #000000;">2</span><span style="color: #0000FF;">,</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #000000;">0</span><span style="color: #0000FF;">},{</span><span style="color: #000000;">7</span><span style="color: #0000FF;">,</span><span style="color: #000000;">2</span><span style="color: #0000FF;">,</span><span style="color: #000000;">8</span><span style="color: #0000FF;">})</span>
<!--</syntaxhighlight>-->
{{out}}
<pre>{7,0,5,4,3,2,1,6}</pre>
<pre>
{7,0,5,4,3,2,1,6}
</pre>
 
=== Shorter Alternative Version ===
<!--<syntaxhighlight lang="phix">(phixonline)-->
<lang Phix>function disjoint_sort(sequence s, sequence idx)
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
return reinstate(s,sort(idx),sort(extract(s,idx)))
<span style="color: #008080;">function</span> <span style="color: #000000;">disjoint_sort</span><span style="color: #0000FF;">(</span><span style="color: #004080;">sequence</span> <span style="color: #000000;">s</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">idx</span><span style="color: #0000FF;">)</span>
end function
<span style="color: #000000;">idx</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">unique</span><span style="color: #0000FF;">(</span><span style="color: #000000;">idx</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">return</span> <span style="color: #7060A8;">reinstate</span><span style="color: #0000FF;">(</span><span style="color: #000000;">s</span><span style="color: #0000FF;">,</span><span style="color: #000000;">idx</span><span style="color: #0000FF;">,</span><span style="color: #7060A8;">sort</span><span style="color: #0000FF;">(</span><span style="color: #7060A8;">extract</span><span style="color: #0000FF;">(</span><span style="color: #000000;">s</span><span style="color: #0000FF;">,</span><span style="color: #000000;">idx</span><span style="color: #0000FF;">)))</span>
?disjoint_sort({7,6,5,4,3,2,1,0},{7,2,8})</lang>
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
same output.
<span style="color: #0000FF;">?</span><span style="color: #000000;">disjoint_sort</span><span style="color: #0000FF;">({</span><span style="color: #000000;">7</span><span style="color: #0000FF;">,</span><span style="color: #000000;">6</span><span style="color: #0000FF;">,</span><span style="color: #000000;">5</span><span style="color: #0000FF;">,</span><span style="color: #000000;">4</span><span style="color: #0000FF;">,</span><span style="color: #000000;">3</span><span style="color: #0000FF;">,</span><span style="color: #000000;">2</span><span style="color: #0000FF;">,</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #000000;">0</span><span style="color: #0000FF;">},{</span><span style="color: #000000;">7</span><span style="color: #0000FF;">,</span><span style="color: #000000;">2</span><span style="color: #0000FF;">,</span><span style="color: #000000;">8</span><span style="color: #0000FF;">})</span>
<!--</syntaxhighlight>-->
{{out}}
<pre>same output.</pre>
 
=={{header|PicoLisp}}==
The indices are incremented here, as PicoLisp is 1-based
<langsyntaxhighlight PicoLisplang="picolisp">(let (Values (7 6 5 4 3 2 1 0) Indices (7 2 8))
(mapc
'((V I) (set (nth Values I) V))
(sort (mapcar '((N) (get Values N)) Indices))
(sort Indices) )
Values )</langsyntaxhighlight>
{{out}}
Output:
<pre>-> (7 0 5 4 3 2 1 6)</pre>
 
=={{header|Prolog}}==
 
=== Using only predicates marked as "builtin" ===
<syntaxhighlight lang="prolog">
 
<lang Prolog>
% ===
% Problem description
Line 1,997 ⟶ 3,174:
insert_fresh_vars(_,[],V,[],[],V).
</syntaxhighlight>
</lang>
 
=== Alternatively, using predicates from <code>library(list)</code> ===
 
Using <code>append/3</code> from SWi-Prolog's [https://eu.swi-prolog.org/pldoc/man?section=lists library(list)]
 
<syntaxhighlight lang="prolog">
<lang Prolog>
% ===
% Main predicate
Line 2,033 ⟶ 3,209:
length(Front, N),
append(Front, [Elem|Back], List).
</syntaxhighlight>
</lang>
 
=== Unit Tests ===
 
Test code using the [https://www.swi-prolog.org/pldoc/doc_for?object=section(%27packages/plunit.html%27) Unit Testing framework of SWI Prolog].
 
<syntaxhighlight lang="prolog">
<lang Prolog>
% We use the "R" intermediate var to decouple processing by the predicate
% from subsequent checking against expected result.
Line 2,069 ⟶ 3,244:
rt :- run_tests(sort_disjoint_sublist).
</syntaxhighlight>
</lang>
 
=={{header|PowerShell}}==
Line 2,075 ⟶ 3,250:
{{works with|PowerShell|4.0}}
 
<syntaxhighlight lang="powershell">
<lang PowerShell>
function sublistsort($values, $indices) {
$indices = $indices | sort
Line 2,085 ⟶ 3,260:
$indices = 6, 1, 7
"$(sublistsort $values $indices)"
</syntaxhighlight>
</lang>
{{out}}
<b>Output:</b>
<pre>7 0 5 4 3 2 1 6</pre>
<pre>
7 0 5 4 3 2 1 6
</pre>
 
=={{header|PureBasic}}==
Based on the C implementation
<lang PureBasic>Procedure Bubble_sort(Array idx(1), n, Array buf(1))
Protected i, j
SortArray(idx(),#PB_Sort_Ascending)
For i=0 To n
For j=i+1 To n
If buf(idx(j)) < buf(idx(i))
Swap buf(idx(j)), buf(idx(i))
EndIf
Next
Next
EndProcedure
 
Procedure main()
DataSection
values: Data.i 7, 6, 5, 4, 3, 2, 1, 0
indices:Data.i 6, 1, 7
EndDataSection
Dim values.i(7) :CopyMemory(?values, @values(), SizeOf(Integer)*8)
Dim indices.i(2):CopyMemory(?indices,@indices(),SizeOf(Integer)*3)
If OpenConsole()
Protected i
PrintN("Before sort:")
For i=0 To ArraySize(values())
Print(Str(values(i))+" ")
Next
PrintN(#CRLF$+#CRLF$+"After sort:")
Bubble_sort(indices(), ArraySize(indices()), values())
For i=0 To ArraySize(values())
Print(Str(values(i))+" ")
Next
Print(#CRLF$+#CRLF$+"Press ENTER to exit")
Input()
EndIf
EndProcedure
 
main()</lang>
<pre>Before sort:
7 6 5 4 3 2 1 0
 
After sort:
7 0 5 4 3 2 1 6</pre>
 
=={{header|Python}}==
The function modifies the input data list in-place and follows the Python convention of returning None in such cases.
 
<langsyntaxhighlight lang="python">>>> def sort_disjoint_sublist(data, indices):
indices = sorted(indices)
values = sorted(data[i] for i in indices)
Line 2,159 ⟶ 3,284:
 
>>> </langsyntaxhighlight>
 
 
Or, checking a dictionary for sublist indices, and returning a new (rather than mutated) list:
<langsyntaxhighlight lang="python">'''Disjoint sublist sorting'''
 
 
Line 2,224 ⟶ 3,349:
 
if __name__ == '__main__':
main()</langsyntaxhighlight>
{{Out}}
<pre>Disjoint sublists at indices [6, 1, 7] sorted:
Line 2,230 ⟶ 3,355:
[7, 6, 5, 4, 3, 2, 1, 0] -> [7, 0, 5, 4, 3, 2, 1, 6]
['h', 'g', 'f', 'e', 'd', 'c', 'b', 'a'] -> ['h', 'a', 'f', 'e', 'd', 'c', 'b', 'g']</pre>
 
=={{header|Quackery}}==
 
<syntaxhighlight lang="Quackery"> [ sort tuck [] unrot
witheach
[ dip dup peek
rot join swap ]
swap sort
dip swap witheach
[ over i^ peek
dip rot poke
swap ]
drop ] is sortdisjointsublist ( [ [ --> [ )
 
' [ 7 6 5 4 3 2 1 0 ] ' [ 6 1 7 ] sortdisjointsublist echo
</syntaxhighlight>
 
{{out}}
 
<pre>[ 7 0 5 4 3 2 1 6 ]</pre>
 
=={{header|R}}==
R lets you access elements of vectors with a vector of indices.
 
<langsyntaxhighlight Rlang="r"> values=c(7,6,5,4,3,2,1,0)
indices=c(7,2,8)
values[sort(indices)]=sort(values[indices])
print(values)</langsyntaxhighlight>
Output:
<pre> 7 0 5 4 3 2 1 6</pre>
 
=={{header|Racket}}==
<syntaxhighlight lang="racket">#lang racket
<lang Racket>
#lang racket
 
(define (sort-disjoint l is)
Line 2,254 ⟶ 3,398:
 
(sort-disjoint '(7 6 5 4 3 2 1 0) '(6 1 7))
;; --> '(7 0 5 4 3 2 1 6)</syntaxhighlight>
</lang>
 
=={{header|Raku}}==
Line 2,262 ⟶ 3,405:
===Inline===
Using L-value slice of the array, and `sort` as a mutating method:
<syntaxhighlight lang="raku" perl6line>my @values = 7, 6, 5, 4, 3, 2, 1, 0;
my @indices = 6, 1, 7;
 
@values[ @indices.sort ] .= sort;
 
say @values;</langsyntaxhighlight>
Output:<pre>[7, 0, 5, 4, 3, 2, 1, 6]</pre>
 
===Iterative===
<syntaxhighlight lang="raku" perl6line>sub disjointSort( @values, @indices --> List ) {
my @sortedValues = @values[ @indices ].sort ;
for @indices.sort -> $insert {
Line 2,282 ⟶ 3,425:
my @indices = ( 6 , 1 , 7 ) ;
my @sortedValues = disjointSort( @values , @indices ) ;
say @sortedValues ;</langsyntaxhighlight>
{{out}}
Output:
<pre>[7, 0, 5, 4, 3, 2, 1, 6]</pre>
 
Line 2,292 ⟶ 3,435:
 
The REXX language normally uses a one-based index.
<langsyntaxhighlight lang="rexx">/*REXX program uses a disjointed sublist to sort a random list of values. */
parse arg old ',' idx /*obtain the optional lists from the CL*/
if old='' then old= 7 6 5 4 3 2 1 0 /*Not specified: Then use the default.*/
Line 2,322 ⟶ 3,465:
$= @.1; do j=2 to n; $= $ @.j
end /*j*/
return $</langsyntaxhighlight>
{{out|output|text=&nbsp; when using the default inputs:}}
<pre> list of indices: 7 2 8
<pre>
list of indices: 7 2 8
 
unsorted list: 7 6 5 4 3 2 1 0
sorted list: 7 0 5 4 3 2 1 6</pre>
</pre>
 
=={{header|Ring}}==
<langsyntaxhighlight lang="ring">
aList = [7, 6, 5, 4, 3, 2, 1, 0]
indList = [7, 2, 8]
Line 2,352 ⟶ 3,493:
next
? "[" + left(svect, len(svect) - 1) + "]"
</syntaxhighlight>
</lang>
{{out}}
<pre>[7, 0, 5, 4, 3, 2, 1, 6]</pre>
<pre>
 
[7, 0, 5, 4, 3, 2, 1, 6]
=={{header|RPL}}==
</pre>
≪ SORT → set
≪ { } 1 set SIZE '''FOR''' j
OVER set j GET GET + '''NEXT'''
SORT SWAP
1 set SIZE '''FOR''' j
set j GET 3 PICK j GET PUT '''NEXT'''
SWAP DROP
≫ ≫ '<span style="color:blue">'''SUBSORT'''</span>' STO
HP-28 models shall use their homemade version of the SORT instruction, or use the one defined in [[Sorting algorithms/Bubble sort#RPL|Sorting algorithms/Bubble sort]]
{ 7 6 5 4 3 2 1 0 } { 6 1 7 } <span style="color:blue">'''SUBSORT'''</span>
{{out}}
<pre>1: { 7 0 5 4 3 2 1 6 }</pre>
 
=={{header|Ruby}}==
By convention, the exlamation mark in the method name indicates that something potentially dangerous can happen. (In this case, the in place modification).
<langsyntaxhighlight lang="ruby">def sort_disjoint_sublist!(ar, indices)
values = ar.values_at(*indices).sort
indices.sort.zip(values).each{ |i,v| ar[i] = v }
Line 2,368 ⟶ 3,521:
values = [7, 6, 5, 4, 3, 2, 1, 0]
indices = [6, 1, 7]
p sort_disjoint_sublist!(values, indices)</langsyntaxhighlight>
{{out}}
Output
<pre>[7, 0, 5, 4, 3, 2, 1, 6]</pre>
 
=={{header|Run BASICRust}}==
<syntaxhighlight lang="rust">use std::collections::BTreeSet;
Normally we sort with SQLite in memory. Faster and less code
<lang runbasic>sortData$ = "7, 6, 5, 4, 3, 2, 1, 0"
sortIdx$ = "7, 2, 8"
 
fn disjoint_sort(array: &mut [impl Ord], indices: &[usize]) {
numSort = 8
let mut sorted = indices.to_owned();
dim sortData(numSort)
sorted.sort_unstable_by_key(|k| &array[*k]);
for i = 1 to numSort
indices
sortData(i) = val(word$(sortData$,i,","))
.iter()
next i
.zip(sorted.iter())
.map(|(&a, &b)| if a > b { (b, a) } else { (a, b) })
.collect::<BTreeSet<_>>()
.iter()
.for_each(|(a, b)| array.swap(*a, *b))
}
 
fn main() {
while word$(sortIdx$,s + 1) <> ""
s let mut array = s[7, +6, 5, 4, 3, 2, 1, 0];
let indices = [6, 1, 7];
idx = val(word$(sortIdx$,s))
disjoint_sort(&mut array, &indices);
gosub [bubbleSort]
println!("{:?}", array);
wend
}</syntaxhighlight>
end
{{out}}
 
<pre>[7, 0, 5, 4, 3, 2, 1, 6]</pre>
[bubbleSort]
sortSw = 1
while sortSw = 1
sortSw = 0
for i = idx to numSort - 1 ' start sorting at idx
if sortData(i) > sortData(i+1) then
sortSw = 1
sortHold = sortData(i)
sortData(i) = sortData(i+1)
sortData(i+1) = sortHold
end if
next i
wend
RETURN</lang>
 
=={{header|Scala}}==
{{libheader|Scala}}<langsyntaxhighlight lang="scala">import scala.compat.Platform
 
object SortedDisjointSubList extends App {
Line 2,422 ⟶ 3,566:
assert(sortSubList(subListIndex, list) == List(7, 0, 5, 4, 3, 2, 1, 6), "Incorrect sort")
println(s"List in sorted order.\nSuccessfully completed without errors. [total ${Platform.currentTime - executionStart} ms]")
}</langsyntaxhighlight>
 
=={{header|Scheme}}==
{{works with|Gauche Scheme}}
<langsyntaxhighlight Schemelang="scheme">(use gauche.sequence)
(define num-list '(7 6 5 4 3 2 1 0))
(define indices '(6 1 7))
Line 2,441 ⟶ 3,585:
num-list)
<
car))</langsyntaxhighlight>
{{output}}
<pre>(7 0 5 4 3 2 1 6)</pre>
<pre>
(7 0 5 4 3 2 1 6)
</pre>
 
=={{header|Sidef}}==
<langsyntaxhighlight lang="ruby">func disjointSort(values, indices) {
values[indices.sort] = [values[indices]].sort...
}
Line 2,456 ⟶ 3,598:
 
disjointSort(values, indices);
say values;</langsyntaxhighlight>
{{out}}
<pre>[7, 0, 5, 4, 3, 2, 1, 6]</pre>
Line 2,463 ⟶ 3,605:
{{works with|SML/NJ}}
{{trans|Go}}
<langsyntaxhighlight lang="sml">functor SortDisjointFn (A : MONO_ARRAY) : sig
val sort : (A.elem * A.elem -> order) -> (A.array * int array) -> unit
end = struct
Line 2,504 ⟶ 3,646:
DisjointViewSort.sort cmp (arr, indices)
)
end</langsyntaxhighlight>
Usage:
<pre>- structure IntArray = struct
Line 2,530 ⟶ 3,672:
{{trans|Go}}
Sorts an array "wrapper" which represents a "view" into the disjoint sublist of the array.
<langsyntaxhighlight lang="swift">struct DisjointSublistView<T> : MutableCollectionType {
let array : UnsafeMutablePointer<T>
let indexes : [Int]
Line 2,555 ⟶ 3,697:
let ind = [6, 1, 7]
sortDisjointSublist(&a, ind)
println(a)</langsyntaxhighlight>
{{out}}
<pre>[7, 0, 5, 4, 3, 2, 1, 6]</pre>
Line 2,561 ⟶ 3,703:
=={{header|Tcl}}==
This returns the sorted copy of the list; this is idiomatic for Tcl programs where values are immutable.
<langsyntaxhighlight lang="tcl">package require Tcl 8.5
proc disjointSort {values indices args} {
# Ensure that we have a unique list of integers, in order
Line 2,575 ⟶ 3,717:
# The updated list is the result
return $values
}</langsyntaxhighlight>
Demonstration:
<langsyntaxhighlight lang="tcl">set values {7 6 5 4 3 2 1 0}
set indices {6 1 7}
puts \[[join [disjointSort $values $indices] ", "]\]</langsyntaxhighlight>
{{out}}
Output:
<pre>[7, 0, 5, 4, 3, 2, 1, 6]</pre>
 
=={{header|TUSCRIPT}}==
TUSCRIPT indexing is one based
<langsyntaxhighlight lang="tuscript">$$ MODE TUSCRIPT
$$ MODE TUSCRIPT
values="7'6'5'4'3'2'1'0"
indices="7'2'8"
Line 2,595 ⟶ 3,736:
values=REPLACE (values,#i,v)
ENDLOOP
PRINT values</syntaxhighlight>
{{out}}
</lang>
<pre>7'0'5'4'3'2'1'6 </pre>
Output:
<pre>
7'0'5'4'3'2'1'6
</pre>
 
=={{header|Ursala}}==
<langsyntaxhighlight Ursalalang="ursala">#import std
#import nat
 
Line 2,610 ⟶ 3,748:
#cast %nL
 
t = disjoint_sort({6,1,7},<7,6,5,4,3,2,1,0>)</langsyntaxhighlight>
{{out}}
output:
<pre><7,0,5,4,3,2,1,6></pre>
 
=={{header|Wren}}==
{{libheader|Wren-sort}}
<langsyntaxhighlight ecmascriptlang="wren">import "./sort" for Sort
 
// sorts values in place, leaves indices unsorted
Line 2,635 ⟶ 3,773:
System.print("Initial: %(values)")
sortDisjoint.call(values, indices)
System.print("Sorted : %(values)")</langsyntaxhighlight>
{{out}}
<pre>Initial: [7, 6, 5, 4, 3, 2, 1, 0]
Sorted : [7, 0, 5, 4, 3, 2, 1, 6]</pre>
 
=={{header|XPL0}}==
<syntaxhighlight lang="xpl0">include xpllib; \for Sort routine
int Values, Indices, J, I, T;
[Values:= [7, 6, 5, 4, 3, 2, 1, 0];
Indices:= [6, 1, 7];
Sort(Indices, 3);
for J:= 3-1 downto 0 do \bubble sort values at Indices
for I:= 0 to J-1 do
if Values(Indices(I)) > Values(Indices(I+1)) then
[T:= Values(Indices(I));
Values(Indices(I)):= Values(Indices(I+1));
Values(Indices(I+1)):= T;
];
for I:= 0 to 8-1 do
[IntOut(0, Values(I)); ChOut(0, ^ )];
]</syntaxhighlight>
{{out}}
<pre>7 0 5 4 3 2 1 6 </pre>
<pre>
Initial: [7, 6, 5, 4, 3, 2, 1, 0]
Sorted : [7, 0, 5, 4, 3, 2, 1, 6]
</pre>
 
=={{header|zkl}}==
<langsyntaxhighlight lang="zkl">values :=T(7, 6, 5, 4, 3, 2, 1, 0);
indices:=T(6, 1, 7);
 
Line 2,650 ⟶ 3,804:
.zip(indices.sort()) //-->(v,i) == L(L(0,1),L(1,6),L(6,7))
.reduce(fcn(newList,[(v,i)]){ newList[i]=v; newList },values.copy())
.println(); // new list</langsyntaxhighlight>
This is an create-new-object version. An in place version is almost identical:
<langsyntaxhighlight lang="zkl">values :=L(7, 6, 5, 4, 3, 2, 1, 0);
 
indices.apply(values.get).sort() // a.get(0) == a[0]
Line 2,658 ⟶ 3,812:
.apply2(fcn([(v,i)],list){ list[i]=v },values);
 
values.println(); // modified list</langsyntaxhighlight>
{{out}}
{{out}}<pre>L(7,0,5,4,3,2,1,6)</pre>
<pre>L(7,0,5,4,3,2,1,6)</pre>
9,479

edits