text:
Sort an Integer List
The Challenge
It's quite simple really, sort a list of numbers.
Details
You must sort a list of numbers in ascending order, without using any built-in sorting functions/libraries/etc (i.e. list.sort() in Python).
Input/output can be done in any method you choose, as long as it is human readable.
Standard loopholes are disallowed as always.
Shortest code in bytes wins.
You must explain/list what sort method you used (Bubble, Insertion, Selection, etc.)
Input will not contain duplicates.
Sample Input/Output
Input: 99,-2,53,4,67,55,23,43,88,-22,36,45
Output: -22,-2,4,23,36,43,45,53,55,67,88,99
Note: A near direct opposite of Sort a List of Numbers

I'm very surprised if this isn't a duplicate, but I don't have the time to check. Anyway, "built-in sorting functions" should be better defined. Can you use a function that indexes all values? [7 2 4 1] -> [4 2 3 1]. Also, can the CSV list be inside brackets? Also, the specific input format is very suitable for some languages, and bad for others. This makes input parsing a big part for some submissions, and unnecessary for others.

@StewieGriffin I've seen many sorting challenges, but none dealing with sorting just a basic integer list. There are many challenges that are easier for some languages, and much more difficult in others.

This is very similar, but has a O(Nlog(N)) restriction.

Very closely related to this question, but since some answers here (e.g. Dennis' range filtering) require the input to be integers I won't vote to close as dupe.

Relevant: https://www.youtube.com/user/AlgoRythmics/videos — An Youtube channel which teaches sorting algorithms through Hungarian dances!

05AB1E, 2 bytes
Code:
œß

Same algorithm as the Jelly answer. Computes all permutations of the input and pops out the smallest one.
Try it online!

A more efficient method is:
E[ß,Ž

Performs selection sort. Uses CP-1252 encoding.
Try it online!

Accepting this temporarily as I don't see anyone getting less than 2.

@MichelfrancisBustillos well, if they did, it would be a builtin, wouldn't it?

I just looked at 05AB1E/Base a minute ago, and then I looked at this. Coincidence?

Jelly, 3 bytes
Œ!Ṃ

This generates all permutations of the input list, then selects the lexographically smallest permutation. Very efficient.
Credits to @Adnan who had the same idea independently.
Try it online!

Jelly, 4 bytes
ṂrṀf

This builds the range from the minimum of the list to the maximum of the list, then discards the range elements not present in the original list. This is technically a bucket sort, with very small buckets. I'm not aware of a name for this specific variant.
Try it online!
How it works
ṂrṀf  Main link. Argument: A (list/comma-separated string)

Ṃ     Compute the minimum of A.
  Ṁ   Compute the maximum of A.
 r    Yield the inclusive range from the minimum to the maximum.
   f  Filter the range by presence in A.

O(very). Uses much sort.

So O. Very uses. Much sort. Amaze! (Sorry, what?)

I'm not great at complexity of algorithms, would this be O(n!)?

@FlipTack Neither am I. Probably a bit higher, since there are n! arrays of length n.

Just selecting the smallest lexographically is O(n*n!) since each of the n! arrays must be compared sequentially, and lexographical comparison is O(n).  Generation can be done in O(n*n!) as well if done efficiently so I would bet the algorithm is only O(n*n!) if well implemented

Python, 46 45 bytes
lambda l:[l.pop(l.index(min(l)))for _ in 1*l]

Simple selection sort.

l[:] could be 1*l

x86-16 machine code (BubbleSort int8_t), 20 19 bytes
x86-64/32 machine code (JumpDownSort) 21 19 bytes
Changelog:

Thanks to @ped7g for the lodsb/cmp [si],al idea, and putting that together with a pointer increment / reset that I'd been looking at.  Not needing al/ah lets us use nearly the same code for larger integers.

New (but related) algorithm, many implementation changes: Bubbly SelectionSort allows a smaller x86-64 implementation for bytes or dwords; break-even on x86-16 (bytes or words).  Also avoids the bug on size=1 that my BubbleSort has.  See below.

It turns out that my Bubbly Selection Sort with swaps every time you find a new min is already a known algorithm, JumpDown Sort.  It's mentioned in Bubble Sort: An Archaeological Algorithmic Analysis (i.e. how did Bubble Sort become popular despite sucking in general for speed).

Sorts 8-bit signed integers in-place.  (Unsigned is the same code size, just change the jge to a jae).  Duplicates are not a problem.  We swap using a 16-bit rotate by 8 (with a memory destination).
Bubble Sort sucks for performance, but I've read that it's one of the smallest to implement in machine code.  This seems especially true when there are special tricks for swapping adjacent elements.  This is pretty much its only advantage, but sometimes (in real life embedded systems) that's enough advantage to use it for very short lists.
I omitted the early termination on no swaps.  I used Wikipedia's "optimized" BubbleSort loop which avoids looking at the last n − 1 items when running for the n-th time, so the outer loop counter is the upper bound for the inner loop.
NASM listing (nasm -l /dev/stdout), or plain source
 2 address  16-bit       bubblesort16_v2:
 3          machine      ;; inputs: pointer in ds:si,  size in in cx
 4          code         ;; requires: DF=0  (cld)
 5          bytes        ;; clobbers: al, cx=0
 6
 7 00000000 49               dec     cx          ; cx = max valid index.  (Inner loop stops 1 before cx, because it loads i and i+1).
 8                       .outer:                 ; do{
 9 00000001 51               push    cx          ;   cx = inner loop counter = i=max_unsorted_idx
10                       .inner:                 ;   do{
11 00000002 AC               lodsb               ;     al = *p++
12 00000003 3804             cmp     [si],al     ;     compare with *p (new one)
13 00000005 7D04             jge     .noswap
14 00000007 C144FF08         rol     word [si-1], 8    ; swap
15                       .noswap:
16 0000000B E2F5             loop    .inner      ;   } while(i < size);
17 0000000D 59               pop     cx          ;  cx = outer loop counter
18 0000000E 29CE             sub     si,cx       ;  reset pointer to start of array
19 00000010 E2EF             loop    .outer      ; } while(--size);
20 00000012 C3               ret

22 00000013  size = 0x13 = 19 bytes.

push/pop of cx around the inner loop means it runs with cx = outer_cx down to 0.
Note that  rol r/m16, imm8 is not an 8086 instruction, it was added later (186 or 286), but this isn't trying to be 8086 code, just 16-bit x86.  If SSE4.1 phminposuw would help, I'd use it.
A 32-bit version of this (still operating on 8-bit integers but with 32-bit pointers / counters) is 20 bytes (operand-size prefix on rol word [esi-1], 8)
Bug: size=1 is treated as size=65536, because nothing stops us from entering the outer do/while with cx=0.  (You'd normally use jcxz for that.)  But fortunately the 19-byte JumpDown Sort is 19 bytes and doesn't have that problem.

Original x86-16 20 byte version (without Ped7g's idea).  Omitted to save space, see the edit history for it with a description.

Performance
Partially-overlapping store/reload (in memory-destination rotate) causes
a store-forwarding stall on modern x86 CPUs (except in-order Atom).  When a high value is bubbling upwards, this extra latency is part of a loop-carried dependency chain.  Store/reload sucks in the first place (like 5 cycle store-forwarding latency on Haswell), but a forwarding stall brings it up to more like 13 cycles.  Out-of-order execution will have trouble hiding this.
See also: Stack Overflow: bubble sort for sorting string for a version of this with a similar implementation, but with an early-out when no swaps are needed.  It uses xchg al, ah / mov [si], ax for swapping, which is 1 byte longer and causes a partial-register stall on some CPUs.  (But it may still be better than memory-dst rotate, which needs to load the value again).  My comment there has some suggestions...

x86-64 / x86-32 JumpDown Sort, 19 bytes (sorts int32_t)
Callable from C using the x86-64 System V calling convention as
int bubblyselectionsort_int32(int dummy, int *array, int dummy, unsigned long size);  (return value = max(array[])).
This is https://en.wikipedia.org/wiki/Selection_sort, but instead of remembering the position of the min element, swap the current candidate into the array.  Once you've found the min(unsorted_region), store it to the end of the sorted region, like normal Selection Sort.  This grows the sorted region by one.  (In the code, rsi points to one past the end of the sorted region; lodsd advances it and mov [rsi-4], eax stores the min back into it.)
The name Jump Down Sort is used in Bubble Sort: An Archaeological Algorithmic Analysis.  I guess my sort is really a Jump Up sort, because high elements jump upwards, leaving the bottom sorted, not the end.
This exchange design leads to the unsorted part of the array ending up in mostly reverse-sorted order, leading to lots of swaps later on.  (Because you start with a large candidate, and keep seeing lower and lower candidates, so you keep swapping.)  I called it "bubbly" even though it moves elements the other direction.  The way it moves elements is also a little bit like a backwards insertion-sort.  To watch it in action, use GDB's display (int[12])buf, set a breakpoint on the inner loop instruction, and use c (continue).  Press return to repeat.  (The "display" command gets GDB to print the whole array state every time we hit the breakpoint).
xchg with mem has an implicit lock prefix which makes this extra slow. Probably about an order of magnitude slower than an efficient load/store swap; xchg m,r is one per 23c throughput on Skylake, but load / store / mov with a tmp reg for an efficient swap(reg, mem) can shift one element per clock.  It might be a worse ratio on an AMD CPU where the loop instruction is fast and wouldn't bottleneck the inner loop as much, but branch misses will still be a big bottleneck because swaps are common (and become more common as the unsorted region gets smaller).
 2 Address               ;; hybrib Bubble Selection sort
 3        machine         bubblyselectionsort_int32:   ;; working, 19 bytes.  Same size for int32 or int8
 4        code               ;; input: pointer in rsi, count in rcx
 5        bytes              ;; returns: eax = max
 6
 7                           ;dec  ecx           ; we avoid this by doing edi=esi *before* lodsb, so we do redundant compares
 8                                               ; This lets us (re)enter the inner loop even for 1 element remaining.
 9                       .outer:
10                           ; rsi pointing at the element that will receive min([rsi]..[rsi+rcx])
11 00000000 56               push   rsi
12 00000001 5F               pop    rdi
13                           ;mov    edi, esi     ; rdi = min-search pointer
14 00000002 AD               lodsd
16 00000003 51               push   rcx          ; rcx = inner counter
17                       .inner:                   ; do {
18                           ; rdi points at next element to check
19                           ; eax = candidate min
20 00000004 AF               scasd                 ; cmp eax, [rdi++]
21 00000005 7E03             jle  .notmin
22 00000007 8747FC           xchg   [rdi-4], eax   ; exchange with new min.
23                         .notmin:
24 0000000A E2F8             loop  .inner          ; } while(--inner);
26                           ; swap min-position with sorted position
27                           ; eax = min.  If it's not [rsi-4], then [rsi-4] was exchanged into the array somewhere
28 0000000C 8946FC           mov    [rsi-4], eax
29 0000000F 59               pop   rcx           ; rcx = outer loop counter = unsorted elements left
30 00000010 E2EE             loop  .outer        ; } while(--unsorted);
32 00000012 C3               ret

34 00000013 13           .size: db $ - bubblyselectionsort_int32
           0x13 = 19 bytes long

Same code size for int8_t: use lodsb / scasb, AL, and change the [rsi/rdi-4] to -1.  The same machine-code works in 32-bit mode for 8/32-bit elements.  16-bit mode for 8/16-bit elements needs to be re-built with the offsets changed (and 16-bit addressing modes use a different encoding).  But still 19 bytes for all.
It avoids the initial dec ecx by comparing with the element it just loaded before moving on.  On the last iteration of the outer loop, it loads the last element, checks if it's less than itself, then is done.  This allows it to work with size=1, where my BubbleSort fails (treats it as size = 65536).
I tested this version (in GDB) using the this caller:  Try it online!.  You can run this it on TIO, but of course no debugger or printing.  Still, the _start that calls it exits with exit-status = largest element = 99, so you can see it works.

There might be room to improve on the inner-loop loop condition, it seems to be using a lot of bytes.  Maybe push/pop cx and use loop for both?  Maybe loop the other way, from back to front of the array so we count an index down to zero?  (And increment bx because the sorted portion is at the end you loop towards).

Got it down to 19B, but with lot of changes, also input regs (some changes probably not needed, but as I was toying around, they remained there from earlier experiments)... it's still based on your work, so reluctant to post it as answer, you can check it on pastebin: https://pastebin.com/0VMzdUjj

@Ped7g: Nice!  I'd considered sub si, cx as part of the outer loop using a pointer instead of indexing, but I hadn't thought of lodsb / cmp [si], al.  I'd been considering lodsw / dec si, or lodsb /xchg al,ahto still set up for cmp ah,al

@Ped7g: oh, your version requires cld, or I guess we could make that part of the calling convention.  AFAIK, having DF cleared is not a standard part of 16-bit calling conventions, only 32/64.  Or is it just that you can't assume it in a bootloader?  But with a custom register calling convention, this is as much of a code fragment as a function, so sure, why not require DF=0.  (And if we want, ES=DS so we could scasb instead of lodsb if that's more convenient.)

I can't recall any 16b calling convention (I never used them, my asm was always custom, using custom set of registers per function, not even having uniform convention), so I don't know about DF either. (as I don't know rules of this site, I may have broken it by using completely custom scheme and DF=0 requirement. But overall; is even x86-16b calling convention a thing? Didn't have pretty much every language compiler its own? I'm pretty sure BorlandC vs WatcomC was not compatible by default, Pascal was different too, DOS int 21h completely custom, etc... it's stone age and anarchy ;) :) )

@Ped7g: I have no idea about 16-bit conventions, all I know is that you couldn't always assume DF was cleared.  But I think that's mostly in a bootloader context.  I've never run anything I've written on real DOS.  I was on Atari Mega 4 STe (68000/68020), then Linux (on a Pentium MMX), so I managed to avoid 16-bit x86 entirely until SO questions rammed it down my throat.

@Ped7g: In pure assembly language, you can make up whatever calling convention you want.  It's only interfacing with compilers or other libraries that you need to stick to any kind of standard.  Thus, an asm function can do whatever you like, IMO as long as it's something you might reasonably expect your caller to do.  (e.g. not copy an arg to multiple registers, but any arbitrary register is fine.)

@Ped7g: Anyway, I updated this answer.  It's pretty common for people to suggest improvements, even major changes, and people edit them into their answers.  That works better for the site than having multiple answers in the same language that use basically the same strategy.  Thanks again.

I went through Z80 (ZX Spectrum) to x86-16, because we had few 286 PC AT computers around at universities in city (where I could "break in" through some adults from family)... did whole "sprite editor" in 320x200 in pure x86-16 at high school, then a friend somewhere downloaded Watcom C and we learned to use DOS4GW for 32b protected mode under DOS ... but our first PC demo was in 16b ... would be lot of pain today, but as I was coming from ZX, it was nice change to have several(!) 64kiB memory banks available, compared to ~39kiB of ZX 48k and 128kiB banking of 128k. 450+kiB RAM = astonishing!

@Ped7g: x86-64 version for 32-bit integers only costs 2 extra bytes.  Your lodsb/cmp idea was key.  IDK if it's reasonable for the function to expect the caller to pass the max idx in the first place, instead of the size.  I don't think anyone would complain, but I'd rather golf this function than "cheat" that way.

@Ped7g: x86-64 version is down to 19 bytes, using a new algo that isn't quite SelectionSort.  (And an xchg with mem to thoroughly destroy performance :P).  It avoids the initial dec ecx by comparing with the element it just loaded before moving on.

Nice tutorial on machine code, and sort algorithms!  And I thought I was hot stuff writing an assembler routine for the Commodore 64 6502 chip!

@MarkStewart: Thanks.  Each machine has code-golf (and performance) tricks that are unique to them, and 6502 especially has some interesting(?) constraints/features like few registers but zero-page memory-indirect addressing that are different from modern CPUs.  So I'm sure there's plenty of fun to be had with 6502 asm / machine code, especially if one is interested in retrocomputing or just code-golf on different historical ISAs.

Brachylog, 12 7 bytes
p.'(s>)

This uses permutation sort, which is obviously terrible, but hey it's shorter than Pyth!
Explanation
p.       Unifies the output with a permutation of the input
  '(  )  True if what's inside the parentheses cannot be proven, else backtrack and
         try with another permutation of the input.
    s    Take an ordered subset from the output
     >   True if the first element is bigger than the second (hence not sorted)
         We don't need to check that the subset is 2 elements long because > will be false
         for inputs that are not 2 elements long anyway

Oracle SQL 11.2, 205 bytes
WITH s AS(SELECT COLUMN_VALUE||''e FROM XMLTABLE(('"'||REPLACE(:1,',','","')||'"'))),v(p,f)AS(SELECT e,e FROM s UNION ALL SELECT p||','||e,e FROM v,s WHERE e+0>f)SELECT p FROM v WHERE LENGTH(p)=LENGTH(:1);

Un-golfed
WITH
s AS  -- Split the string using ',' as separator
(     -- ||'' cast the xml type to varchar
  SELECT COLUMN_VALUE||''e FROM XMLTABLE(('"'||REPLACE(:1,',','","')||'"'))
),
v(p,f) AS  -- Recursive view : p = sorted string, f last number added
(
  SELECT e,e FROM s -- use each number as seed
  UNION ALL         -- only add a number if it is > the last added
  SELECT p||','||e,e FROM v,s WHERE e+0>f  -- +0 is needed to compare int and not strings
)
-- The valid string has the same length as the input
SELECT p FROM v WHERE LENGTH(p)=LENGTH(:1)

As for what sort method it is, I have no idea, ORDER BY made sure I forgot them.

I barely know SQL, but from your comments I think you're selecting the min or max from the remaining unsorted elements, and appending that to the end of a sorted list.  That makes this a https://en.wikipedia.org/wiki/Selection_sort.

Haskell, 38 bytes
h%t|(a,b)<-span(<h)t=a++h:b
foldr(%)[]

The binary function % insert a new element h into a sorted list t by partitioning t into a prefix a of elements <h and a suffix b of elements >h, and sticks in h between them.
The operation foldr(%)[] then builds up a sorted list from empty by repeatedly inserting elements from the input list.
This is one byte shorter than the direct recursive implementation
f(h:t)|(a,b)<-span(<h)$f t=a++h:b
f x=x

Another strategy for 41 bytes:
f[]=[]
f l|x<-minimum l=x:f(filter(/=x)l)

So this is https://en.wikipedia.org/wiki/Insertion_sort, with % as the insertion inner loop and foldr to apply it as the outer loop.

JavaScript (ES6), 51 bytes
a=>a.map(_=>m=Math.min(...a.filter(e=>e>m)),m=-1/0)

Each loop finds the smallest number that hasn't been found so far.

Calling this on [1,2,3,4,5,4,3,2,1] produces [1, 2, 3, 4, 5, Infinity, Infinity, Infinity, Infinity]

@BenjaminGruenbaum "Input will not contain duplicates."

I have the exact same bytecount with a different approach

Actually, 1 byte less

This algorithm is a https://en.wikipedia.org/wiki/Selection_sort

Haskell, 42 41 38 bytes
f u=filter(`elem`u)[(minBound::Int)..]

Loops through all integers (signed 64bit, on my machine) and keeps those that are in u. Of course it doesn't finish in reasonable time.
The previous version looped through [minimum u..maximum u] which has the same worst case running time.
Edit: @xnor saved a byte. Thanks!

filter is one shorter: f u=filter(`elem`u)[minimum u..maximum u]

How brute force! Does [minimum u..] not work for type reasons?

@xnor: I think so. When calling, let's say f [1,3,0], the elements default to type Integer which is unbound, so the .. never ends. If you have to call it like f ([1, 3, 0]::[Int]) then I guess, the type annotation has to be included in the byte count.

How does it detect elements that occur more than once?

@feersum: it doesn't, but the challenge says: "Input will not contain duplicates".

Python 2, 34 bytes
def f(s):m=min(s);print m;f(s-{m})

Takes input as a set, printing its elements in increasing order, terminating with error.
A clean termination can be done in 41 bytes:
def f(s):
 if s:m=min(s);print m;f(s-{m})

or
l=input()
while l:m=min(l);print m;l-={m}

The input can be take as a list for 39 bytes, or 38 bytes in Python 3.5:
def f(l):m=min(l);print m;f(set(l)-{m})
def f(l):m=min(l);print(m);f({*l}-{m})

This is a https://en.wikipedia.org/wiki/Selection_sort, using m=min(s) / s - (m) as the inner loop to find and remove the min from the unsorted elements, and recursion as the outer.

C, 72 bytes
i,j;a(int*l,int n){for(i=0;i=i?:--n;j>l[n]?l[i]=l[n],l[n]=j:0)j=l[--i];}

Bubblesort. The first argument is a pointer to the array, the second argument is the length of the array. Works with gcc.

This really needs an ungolfed version to be readable; it's really hard to keep track of where the ternary operators start / end.

Python 3, 91 62 47 bytes
def f(z):
 while z:m=min(z);z.remove(m);yield m

Thanks to wnnmaw and Seeq for golfing help.
The argument z should be a list. This is a variant of selection sort.
I'm not sure how min stacks up against built-in sorting functions, since I'm not sure how Python implements min. Hopefully, this solution is still okay. Any golfing suggestions in the comments or in PPCG chat are welcome.

Make sure to state what type of sort you are using.

@MichelfrancisBustillos I've honestly forgotten what algorithm this is. Might be selection sort?

Just out of curiosity, why not just directly take a list? The question allows for open input format

@wnnmaw Dang it, I wrote one up but forgot to post it. Thanks for the reminder :D

Hmm, maybe def f(z):\nwhile z:m=min(z);z.remove(m);yield m

This is definitely https://en.wikipedia.org/wiki/Selection_sort.  It scans the entire remaining list of elements for the min element (using m=min(z);), and returns it as the next generated value with yield.  min() implements the inner loop of Selection Sort, while z: implements the outer loop.  .remove may be a lot less efficient than swapping the new min into place (remove has to find it again), but it's still Selection in a loop.

MATL, 11 10 bytes
Y@t!d0>AY)

Extremely inefficient examination of all permutations of the input.
Try it Online!
Explanation
        % Implicitly grab input array
Y@      % Compute all permutations (each permutation as a row)
t       % Duplicate this matrix
!d      % Transpose and take the differences between the values
0>A     % Find the rows where all differences are > 0
Y)      % Return only the row where this is true
        % Implicitly display the result

Python, 120 Bytes
def f(a):import time,threading;[threading.Thread(None,lambda b=b,c=min(a):print(time.sleep(b-c)or b)).start()for b in a]

This probably won't be the shortest answer but I feel like this algorithm belongs here. call with a list of integers, they'll be printed in a sorted manner to stdout. I wouldn't try it with too large numbers though.

Nice first post! And nice username. :P

Ruby, 40 bytes
Selection sort. Anonymous function; takes the list as argument.
->a{r=[];r<<a.delete(a.min)while[]!=a;r}

Awk, 66 bytes
{b=$0;a[b]}m<b{m=b}n>b{n=b}END{for(i=n;i<=m;i++)if(i in a)print i}

Arrays in awk are like dictionaries, not like C arrays. The indexes can be non-contiguous, and they grow (and are created) as needed. So, we create an array a for the input, with each line being a key. And we save the min and max values. Then we loop from min to max, and print all keys which exist in a. b is just to avoid repeated usage of $0.

This is a couple chars shorter...
!a[b=$0]&&m<b{m=b}n>b{n=b}END{for(;n<=m;n++)if(n in a)print n}

Pyth - 15 13 11 10 bytes
Two bytes saved thanks to @Jakube.
Bogosort.
f!s>VTtT.p

Try it online here.
I don't need the h cuz we are guaranteed no duplicates.

@Jakube I feel stupid, thanks.

@Suever as I said in my answer, we are guaranteed no duplicates as per OP.

Sorry about that! Missed that point.

MATL, 11 bytes
`t4#X<2#)tn

Try it online!
This sorts by the following procedure, which is O(n2):

Take the minimum of the array.
Remove that value from the array, and store it for subsequent display.
Apply the same procedure with the rest of the array, until it becomes empty.
Display all numbers in the order in which they were obtained.

MATL is stack-based. The array with remaining values is kept at the top of the stack. The removed values are below, in order. At the end of the program all those values are displayed. The array at the top would also be displayed, but since it's empty it's not shown.
`        % Do...while loop
  t      %   Duplicate. Implicitly take input in the first iteration
  4#X<   %   Compute index of mininum of the array
  2#)    %   Push the minimum, and then the array with remaining entries
  tn     %   Duplicate and push number of elements, to be used as loop condition
         % Implicitly end do...while loop
         % Implicitly display stack contents

Java 8, 112 92 bytes
Here is another selection sort. The input is a List t of integers and the sorted output is printed to standard out.
t->{for(;0<t.size();System.out.println(t.remove(t.indexOf(java.util.Collections.min(t)))));}

Update

-20 [16-08-21] Used a lambda

Hi Nonlinear, and welcome to PPCG!

Welcome to Programming Puzzles & Code Golf! It appears your code assumes a variable t to exist, which makes it a snippet; we require submissions to be full programs or functions which utilize our default I/O formats. We also require imports to factor into the byte count. Let me know if you have any questions!

Thanks for the resources! I modified my answer to be a function and to include the import.

MIPS, 68 bytes
I wrote a simple unoptimized bubble sort implementation a while ago. Byte count begins at loop and ends at li $v0, 10, assuming that the list address and list length are already in memory.
 Address    Code        Basic                     Source

0x00400000  0x3c011001  lui $1,4097           5    main:   la      $s0, list       # List address
0x00400004  0x34300000  ori $16,$1,0
0x00400008  0x2411000a  addiu $17,$0,10       6            li      $s1, 10         # List length
0x0040000c  0x24080000  addiu $8,$0,0         8    loop:   li      $t0, 0          # swapped
0x00400010  0x24090001  addiu $9,$0,1         9            li      $t1, 1          # for loop "i"
0x00400014  0x1131000b  beq $9,$17,11         11   for:    beq     $t1, $s1, fend  # break if i==length
0x00400018  0x00095080  sll $10,$9,2          13           sll     $t2, $t1, 2     # Temp index, multiply by 4
0x0040001c  0x01505020  add $10,$10,$16       14           add     $t2, $t2, $s0   # Combined address
0x00400020  0x8d4b0000  lw $11,0($10)         15           lw      $t3, 0($t2)     # list[i]
0x00400024  0x8d4cfffc  lw $12,-4($10)        16           lw      $t4, -4($t2)    # list[i-1]
0x00400028  0x21290001  addi $9,$9,1          18           addi    $t1, $t1, 1     # i++
0x0040002c  0x016c082a  slt $1,$11,$12        20           ble     $t4, $t3, for   # if list[i-1] > list[i]
0x00400030  0x1020fff8  beq $1,$0,-8
0x00400034  0xad4bfffc  sw $11,-4($10)        21           sw      $t3, -4($t2)    # swap and store
0x00400038  0xad4c0000  sw $12,0($10)         22           sw      $t4, 0($t2)
0x0040003c  0x24080001  addiu $8,$0,1         23           li      $t0, 1          # swapped=true
0x00400040  0x08100005  j 0x00400014          24           j       for
0x00400044  0x20010001  addi $1,$0,1          26   fend:   subi    $s1, $s1, 1     # length--
0x00400048  0x02218822  sub $17,$17,$1
0x0040004c  0x1500ffef  bne $8,$0,-17         27           bnez    $t0, loop       # Repeat if swapped==true
0x00400050  0x2402000a  addiu $2,$0,10        29           li      $v0, 10
0x00400054  0x0000000c  syscall               30           syscall

Now I wait to be blown out of the water with x86...

You can leave out the swapped=true early-out check and count down based on the array size.  See my 20 byte x86-16 version that sorts 8-bit integer.  I might make a normal 32 or 64-bit x86 version that sorts 32-bit integers at some point, but 8-bit integers in 16-bit mode is kind of a sweet spot  for x86.

Julia, 28 27 bytes
x->colon(extrema(x)...)∩x

Try it online!

Does this build a range from min to max, and intersect with the original list?  That would be a flavour of https://en.wikipedia.org/wiki/Counting_sort, like a couple other answers: https://codegolf.stackexchange.com/a/117648/30206.  (The question does specifically require answers to say what kind of sort it is.)

Seriously, 6 bytes
,;l@╨m

Try it online!
This does the same thing as many other answers: generate all permutations, select minimum. I kinda forgot that this would work while I was working on the below solution.
Explanation:
,;l@╨m
,;l@    push len(input), input
    ╨m  minimum permutation

Seriously, 25 bytes (non-competing)
This would be competitive if it wasn't for a bug in the shuffle command that I just fixed.
,1WX╚;;pX@dXZ`i@-0<`MπYWX

Try it online!
This implements the best sorting algorithm ever: Bogosort!
Explanation:
,1WX╚;;pX@dXZ`i@-0<`MπYWX
,                          get input
 1W                    WX  do-while:
   X                         discard
    ╚                        shuffle
     ;;                      dupe twice
       pX@dX                 remove first element of first dupe and last element of second dupe
            Z                zip
             `i@-0<`MπY      test if all differences are positive (if any are not, the list is not sorted), negate (1 if not sorted else 0)

MATL, 17 16 bytes
Saved one byte creating null array thanks to @LuisMendo
vTbtX<-QI$(f8M+q

Bucket sort. Don't try it with a range greater than 231-1.
Try it online!
Explanation
v                  % push an empty array
 T                 % push 1
  b                % bubble the input array up to the top of the stack
   t               % duplicate it
    X<             % find the minimum
      -            % subtract min from input array
       Q           % and increment to adjust for 1-based indexing
        I$(        % resulting array used as indices of empty array
                   % (the [] way up at the top) that are assigned 1 (from T)
           f       % find the nonzero indices
            8M     % magically retrieve the 4th previous function input :/
                     (aka, the min input array value)
              +    % add it to the indices
               q   % and decrement

TIL:

You can initialize an empty array in MATL using [] and grow it, just like in MATLAB
How to use ( for assignment indexing
How to use the M automatic clipboard

New day, new TIL:

vertcat magically creates an empty array when there's nothing on the stack to concatenate

Add to your TIL: an initial [] can be replaced by v. This is because the default number of inputs of v is the number of elements in the stack

@LuisMendo Sooo... if there is one array on the stack... ? Investigating.

Then it does nothing. Think of it as vertcat(STACK{:})

R, 68 Bytes
Takes input i and outputs o which is the sorted list.
o<-i
for(j in 1:length(i)){
x<-(i-min(i))==0
o[j]<-i[x]
i<-i[!x]
}
o

Explanation:
o<-i                      # Defines output as o
 for(j in 1:length(i)){   # Initializes loop for length of input
  x<-(i-min(i))==0        # Generates logical vector by finding the value 0
                          # of input less the minimum of input.
   o[j]<-i[x]             # Puts the smallest value at position j
    i<-i[!x]              # Removes the smallest value from input
      }                   # Ends loop
       o                  # Returns sorted list

Avoiding the permutations means it can sort large lists relatively quickly. The "trick" is that subtracting the smallest value from the input leaves a single 0 that determine both the smallest value and the position of the smallest value.

Clojure, 73 35 bytes
Bogosort :)
#(if(apply < %)%(recur(shuffle %)))

Earlier version:
#(reduce(fn[r i](let[[a b](split-with(partial > i)r)](concat a[i]b)))[]%)

Reduces to a sorted list r by splitting it into "smaller than i" and "larger than i" parts. I guess this is the insertion sort.

Nice! I did not know you could recur on an anonymous function. Also didn't know about shuffle.

R, 47 bytes
implements bogosort.
function(l){while(is.unsorted(l))l=sample(l);l}

Try it online!

Python 3, 53 bytes
lambda l:[i for i in range(min(l),max(l)+1)if i in l]

Try it online!

This is essentially a bucket sort, right? So it fails if the input doesn't fall in the range of the hash table size? Can that happen?

@Jakob I don't think so? To me it's just a range between min and max values, filtered with the input list

@ASCII-only: agreed. Filtering the range between min and max looks like an implementation of https://en.wikipedia.org/wiki/Counting_sort to me, because it's sort of like making a histogram.  (Same as @Mendeleev's Ruby answer)

Retina, 95
Modified bubble sort.  I suspect there are much better ways to do this, even without the retina sort builtin.
-\d+
$*n
\d+
$*11
+`(1+) (n+)
$2 $1
+`\b(n+) (\1n+)|(1+)(1+) \3\b
$2$3 $1$3$4
1(1*)
$.1
n+
-$.&

Stage 1 - convert -ve integers to unary with n as the digit; drop the - signs.
Stage 2 - convert +ve and zero integers to unary with 1 as the digit; add 1 to each one, so that zero is represented by 1.
Stage 3 - Move all -ves to the front.
Stage 4 - Sort: move all -ves with the largest magnitude (i.e. smallest numerical) ahead of higher -ves.  Move smaller +ves ahead of larger +ves.
Stage 5 - Remove 1 from, and convert +ve unaries back to decimal.
Stage 6 - convert -ve unaries back to decimal, including sign.

Try it online.

Just one byte shorter!

@LeakyNun That doesn't sort the last element in the list.

@mbomb007 right, never mind.

Ruby, 22 bytes
A quick permutation sort. Runs in O(n!) space and time.
->a{a.permutation.min}

Java 7, 106 104 bytes
void a(int[]a){for(int b=a.length-1,d=0,c=0,e;d<b*b;c=++d%b)if(a[c]>a[c+1]){e=a[c];a[c++]=a[c];a[c]=e;}}

Here's a good ole bubble sort. The function parameter is modified in place so I don't have to return anything. Still trying to squeeze some bytes out of this so I can beat the java lambda that someone posted.
-1 byte thanks to Geobits for pointing out that normal swapping beats xor'ing

-1 byte thanks to Leaky Nun for pointing out that I can move all the int declarations into the for-loop
Try it online!

Ruby, 26 24 bytes
Selection sort, similar to Value Ink's answer, but using a different approach for greater golfiness.
According to the specification: "Input/output can be done in any method you choose, as long as it is human readable". I think this fits the description, output is an array of arrays with a single element.
->l{l.map{l-l-=[l.min]}}

example:
->l{l.map{l-l-=[l.min]}}[[2,4,3,1]]
=> [[1], [2], [3], [4]]

Ruby, 22 bytes
->a{[*a.min..a.max]&a}

Builds an array out of the range between the minimum and maximum elements of the input array. Returns the intersection between the two arrays.

I guess that's a kind of https://en.wikipedia.org/wiki/Counting_sort.

@PeterCordes That was kinda the point

The question asks you to describe what kind of sort it is, so I thought it was useful to link to the well-known algorithm as well as just describing what it actually does.

True. Thanks @PeterCordes

Jolf, 13 bytes
Uses bogosort. Try it out here! Replace ⌂ with \x7f. Input is a comma-separated list of numbers like 5,3,2,4,1.
W⌂Z,k)ok Tk}k

Explanation:
W⌂Z,k)ok Tk}k
W    )         while
 ⌂Z,            !isSorted
    k            input {
      ok          k =
        _Tk        shuffle(k)
           }   }
            k  out k

Python 2, 159
Implements bozosort (randomly swap two elements until the array is sorted).
It's not very efficient...
from random import randint as r
def b(l):
 s,a=len(l)-1,0
 while not a:
        c,d=r(0,s),r(0,s);l[d],l[c]=l[c],l[d];e,a=l[0],1
        for f in l:a,e=a*(f>=e),f
 return l

you can save a couple of bytes by indenting s,a=..., while not a: and return l with a single space, and the contents of the while loop with a single tab because tab is considered deeper indentation than space. that will make this answer python2 only, though

@undergroundmonorail Thanks!

You can probably use while a<1, or if a is always 0 or 1, you can use while~-a

Javascript 55 bytes
a=>[...a].map(b=>a.splice(a.indexOf(Math.min(...a)),1)

Doesn't work for me on Firefox; for the sample input I get [[-22], [-2], [4], [23], [36], [43], , , , , , ,].

@Neil yeah, missed something

Tcl, 49:  sleep sort
The examples so far aren't very consistent in how they take input, so this sorts command-line arguments.  On particularly slow systems, where the foreach takes more than a millisecond, it might need three extra bytes (after ${x}0).
foreach x $argv {after $x puts $x}
vwait forever

SmileBASIC, 79 bytes
DEF S A
FOR Z=0TO I
FOR I=1TO LEN(A)-1SWAP A[I-(A[I-1]>A[I])],A[I]NEXT
NEXT
END

It's bubble sort but instead of checking to see if it's finished, it just assumes that every input is the worst case and does n^2 (actually n*(n+2)) iterations.

IDK if it saves bytes in your case, but BubbleSort leaves the last Z elements sorted, so you can use the outer loop counter as the inner loop bound (if the outer loop counts down), like https://en.wikipedia.org/wiki/Bubble_sort#Optimizing_bubble_sort describes.  (See my well-commented x86 asm bubblesort)

Perl 5, 65 bytes
Insertion sort subroutine:
sub r{map{$t=0;$_[$_]<$_[$t]&&($t=$_)for 0..$#_;splice@_,$t,1}@_}

Try it online!

Dodos, 75 bytes
	/
/
	/ s w
w
	h
	/ t
s
	s R
R
	t
	h
h
	t I q
q
	dot t
	dot
I
	I dip
t
	dab

Try it online!
Only support non negative integers. Terrible runtime, especially for large numbers.

Explanation
First, define t to be the tail of a list. (all elements except the first)
Given a list [x,y] where x<y, function I computes the incremental difference (with a 0 prepended), which is used in h (head of a list, by getting the sum of all elements, subtract by the sum of all elements except the first)
Function R reverses a list of 2 elements. (concatenate the tail and the head) Generally, it rotates the first element to the last.
s sorts a list of 2 elements. Generally, given a list, it find the least non negative n such that rotate the list left by n make the list less than itself Red.
/ sorts a list of arbitrarily many elements, by / the list' tail, and then / s the result.

Haskell, 97 bytes
s=f.map pure
a@(x:y)!b@(z:w)|x>z=z:a!w|0<1=x:y!b
a!b=a++b
d(x:y:z)=x!y:d z
d p=p
f[x]=x
f x=f$d x

Try it online!
A stable, incremental merge sort.

Pyth, 8 bytes
_ueg#G.p

Try it online!

ueg#G.p:

u Repeatedly apply the following function to the input until the result stops changing.
.p: Generate all permutations of the current list
g#G:

#: Filter the list of permutations
g: On being greater than or equal to
G: The current list

e: Take the last permutation in the filtered list. This will only be the same as the current list if the filter only leaves behind one list, because the permutation function .p always puts its input first.

At this point, we have the maximum permutation of the input, which is in reverse sorted order. _ reverses that to give the sorted list.

Note that Pyth does not have an opposite of g - there is no less than or equal to builtin.

I wanted to see what the intermediate lists are when sorting with this method. Putting a newline at the end of the code prints all of the intermediate lists:
Try it online!
For the input [0,7,4,1,6,5,2,3], here's what the intermediate lists look like:
[0, 7, 4, 1, 6, 5, 2, 3]
[3, 2, 5, 6, 1, 4, 7, 0]
[7, 0, 4, 1, 6, 5, 2, 3]
[7, 3, 2, 5, 6, 1, 4, 0]
[7, 4, 0, 1, 6, 5, 2, 3]
[7, 5, 3, 2, 6, 1, 0, 4]
[7, 6, 4, 0, 1, 2, 3, 5]
[7, 6, 5, 3, 2, 1, 0, 4]
[7, 6, 5, 4, 0, 1, 2, 3]
[7, 6, 5, 4, 3, 2, 1, 0]
[0, 1, 2, 3, 4, 5, 6, 7]

Basically, what's happening is that at each step, the (reverse) sorted prefix stays, and then the last number larger than the front unsorted number is moved to the front of the unsorted region, and the rest of the unsorted region is reversed. It's like a low-quality selection sort with reversals thrown in for fun.
I think this runs in approximately O(n^2 n!) time - n! permutations, n comparisons each, and O(n) rounds (at most 2n, from what I can tell.

minigolf, 48 bytes
Implements insertion sort.
0,;i,:#1,;ns,s,n2,;:,n_T*+0s,,_1_,o_,n__n1+,;o__

Try it online!
Explanation
0,;         Begin from an empty `sorted` list
i,          For each item in input list:
  :#1,;       Duplicate, and wrap `sorted`'s length
              in a singleton list
              (that is to be used later in a 'fry' structure)

  ns          Push current foreach item, and swap it below the length
  ,           'Fry' the input list's length inside
              (accessed with n; singleton lists only loop once)

              Note: at this point the remaining items on the stack are the `sorted` list and the current item of the outer foreach loop.
    s           Swap outer foreach loop item below the `sorted` list
    ,           Foreach item in the sorted list:
      n           Push current foreach item in `sorted` list
      2,;         Pair (but reversed); to implement a conditional swap
                  if the pair happens to be in decreasing order at any point in our loop
      :           Duplicate it, to perform a conditional check
      ,n_         Dump the pair onto the stack
      T*+         Subtract them

      0s          Swap 0 underneath
      ,,_1_       Repeat n times: drop & push 1
                  So if the left item in the pair > right item in the pair,
                  We would definitely execute the next conditional 1 time.

      ,o_         Execute (0 pr 1 times) based on our previous value: reverse the pair
      ,n_         Dump the pair onto the stack
    _           End foreach loop over sorted list
                (We're now in our 'fry' structure.)
    n           Push the length of our previous `sorted` list
    1+          Add 1 to that
    ,;o         Wrap last n items into a list,
                and reverse it back into the right order
                (Now we have a new `sorted` list for the next iteration of the foreach loop.)
  _           End fry sequence
_           End foreach loop in input list

Javascript, 49 Bytes
a=>a.map(c=>setTimeout(alert,c-Math.min(...a),c))

Basic sleep sort implementation. Takes input as an array and outputs as alerts.

Won't this fail for negative integers in the array?

@Shaggy This is accounted for via -Math.min(...a), which, for the case in which the smallest value is -5, would shift all values up by 5, ensuring this still works.

Thunno 2 M, 2 bytes
lṗ

Try it online!
Port of Adnan's 05AB1E answer.
Explanation
lṗ  # Implicit input
l   # Length of input
 ṗ  # Permutations with that length
    # Implicit output of minimum

Vyxal, 14 bitsv1, 1.75 bytes
⇧İ

Try it Online!
Grade up technically doesn't sort the list, but rather gives the position of the first minimum, followed by the position of the second most minimum, followed by the position of the third most minimum and so on.
Explained
⇧İ
⇧  # Grade up the list
 I # and index into the input

Desmos, 99 80 bytes
-19 thanks to Aiden Chow!
Unfortuantely Desmos does not have great capabilities for my favorite sorting algorithm, so here is an implementation of counting sort!
m=A.min
r=[m...A.max]
f(A)=[r[∑_{n=m}^rA[A=n].length=i][1]fori=[1...A.length]]

Try it on Desmos!
How it works:
\$m\$ is just a shorthand for \$A.\operatorname{min}\$ to shave off a few bytes from the code. Note that we are referring to \$A\$ even when it is not defined in this context, but this still works due to some wacko variable scoping.
\$r\$ is also a shorthand for the range \$[m\dots A.\operatorname{max}]\$. This expression appears twice so we can also shave off yet a few more bytes with this.
Next comes the actual sorting procedure:
f(A)=[r[∑_{n=m}^rA[A=n].length=i][1]fori=[1...A.length]]
     [                              fori=[1...A.length]]  repeat for i∈[1,A.length]
      r[                        ]                         filter r
        ∑_{n=m}^r                                         sum from min to r
                 A[A=n].length                            # of occurrences of n
                              =i                          sum=i
                                 [1]                      take the first result

Still doesn't make sense? Let's review the algorithm:

counting sort: count the occurrences of each value and reassemble them in order

# of occurrences is always 0 or 1 since every element is distinct

instead of reassembling, we construct the sorted array on the spot

how? figure out where each element should be
since we know the number of times each element occurs, we can add up the past occurrences to get the sorted index of the current element
now we just look for the element with the specified index (and repeat this for every index)

For example:
A = [ 3 2 9 5 ]

             i ->  1 2 3 4 5 6 7 8
             r = [ 2 3 4 5 6 7 8 9 ]
 A[A=i].length = [ 1 1 0 1 0 0 0 1 ]  number of occurrences
∑A[A=i].length = [ 1 2 2 3 3 3 3 4 ]  cumulative sum/new index

Now for each index \$i\$ in the final sorted array we look for the first item in \$r\$ for which \$\sum A[A=i].\operatorname{length}=i\$. This gives all the elements in the original list, but in sorted order.

80 bytes

TI-Basic, 42 41 bytes
Ans→A
cumSum(seq(sum(Ans=I),I,min(Ans),max(Ans
min(ʟA)+seq(sum(Ans<I),I,1,dim(ʟA

Counting sort. Takes input in Ans. Fails if the range is greater than the list size limit.

45 44 bytes
Ans→A
While 0>min(ΔList(augment(Ans,{max(Ans
randIntNoRep(1,dim(Ans
seq(ʟA(Ans(I)),I,1,dim(Ans
End
Ans

Bogosort. Takes input in Ans. Only works on calculators where randIntNoRep( is supported. For lists with more than one element, you can replace augment(Ans,{max(Ans with Ans for -5 bytes.

63 bytes
Prompt A
For(I,1,dim(ʟA
For(J,I,dim(ʟA
ʟA(I→T
If Ans>ʟA(J:Then
ʟA(J→ʟA(I
T→ʟA(J
End
End
End
ʟA

Similar method to this answer, though I'm not sure if it's exactly bubble sort as the elements it compares aren't always adjacent.

72 71 bytes
Ans→A
For(I,1,dim(Ans)-1
min(Ans→ʟB(I
sum(not(cumSum(ʟA=Ans
seq(ʟA(I+(I>Ans)),I,1,dim(ʟA)-1→A
End
Ans(1→ʟB(I:ʟB

Selection sort. Takes input in Ans. For lists with more than one element, you can replace Ans(1→ʟB(I:ʟB with augment(ʟB,Ans for -6 bytes.

I think you can do Ans→A

Julia, 58 29 bytes
r(A,B=[])=A>[] ? (push!(B,popat!(A,argmin(A)));r(A,B)) : B
!A=A.|>_->popat!(A,argmin(A))

Attempt This Online!

an out-place selection sort
shortened slightly considerably by @MarcMush

Slightly simplified !A=A.|>_->popat!(A,argmin(A))

ReRegex, 78 bytes
(_+),-(_+)/-$2,$1/-(_+),-\1(_+)\b/-$1$2,-$1/(?<!-)(_+)(_+),\1\b/$1,$1$2/#input

Try it online!
Essentially a Parallel Bubble-sort. Takes input as Signed Unary. Much of the program is just edge-cases for signed integers, without them this is just:
Unsigned, 28 bytes
(_+)(_+),\1\b/$1,$1$2/#input

Try it online!

Tcl, 160 bytes
set i 0
time {incr j;set x 0;while \$x<$i {if [lindex $L $i]<[lindex $L $x] {set L [lreplace [linsert $L $x [lindex $L $i]] $j $j]};incr x};incr i} [llength $L]

Try it online!
Without even thinking on a "standard" method, I implement it by using Insertion Sort.

C#, 125 bytes
using System.Linq;x=>{for(int i=0;i<x.Count;i++){int temp=x.GetRange(i,x.Count-i).Min();x[x.IndexOf(temp)]=x[i];x[i]=temp;}};

It uses the selection sort. I don't need to return the sorted list, because in C# lists are reference types, so the variable only holds a reference to the actual object, and if I change the object from here, it'll be visible at other places, as described in this stackoverflow question.

Attache, 36 bytes
{If[#_,Min[_]'$[Remove[_,Min!_]],_]}

Try it online!
Selection sort. Recursively sorts the list by concatenating the minimum with the sorted removed list.

JavaScript, 42 bytes
a=>Object.keys(a.reduce((o,k)=>o[k]=o,{}))

Note: doesn't work for negative numbers.  The iteration order of an object's keys are defined as such in the current spec, requiring that all numerical indexes are iterated in sorted numerical order first.

Haskell, 3332 bytes
import Data.Set
s=elems.fromList

Try it online!

Javascript
for(i=0;i<size;i++){for(j=i+1;j<size;j++){if(num[i]>num[j]){swap=num[j];num[j]=num[i];num[i]=swap;}}}for(i=0;i<size;i++)console.log(num[i])
Here's an implementation of bubble sort.

Japt -m, 9 bytes
M=Wk§M rm

Try it

C# (Visual C# Interactive Compiler), 77 bytes
a=>{for(int@i=0,t;++i<a.Count;)if((t=a[i-1])>a[i]){a[i-1]=a[i];a[i]=t;i=0;}};

Try it online!

Itr, 9 bytes
äRm«â-ÍÌ+
online-interpreter
Explanation
äRm«â-ÍÌ+  ; implicit input
ä          ; duplicate the input
 Rm«       ; get the smallest element
    â      ; push a copy of the element below the list
     -     ; subtract the smallest element from the list
      Í    ; create list with 1's at the positions given by the list
       Ì   ; get the positions of the ones (in ascending order)
        +  ; add back the minimum element


text:
Expand a C array
In the C programming language, arrays are defined like this:
int foo[] = {4, 8, 15, 16, 23, 42};      //Foo implicitly has a size of 6

The size of the array is inferred from the initializing elements, which in this case is 6. You can also write a C array this way, explicitly sizing it then defining each element in order:
int foo[6];        //Give the array an explicit size of 6
foo[0] = 4;
foo[1] = 8;
foo[2] = 15;
foo[3] = 16;
foo[4] = 23;
foo[5] = 42;

The challenge
You must write a program or function that expands arrays from the first way to the second. Since you are writing a program to make code longer, and you love irony, you must make your code as short as possible.
The input will be a string representing the original array, and the output will be the expanded array-definition. You can safely assume that the input will always look like this:
<type> <array_name>[] = {<int>, <int>, <int> ... };

"Type" and "array_name" will made up entirely of alphabet characters and underscores _. The elements of the list will always be a number in the range -2,147,483,648 to 2,147,483,647. Inputs in any other format do not need to be handled.
The whitespace in your output must exactly match the whitespace in the test output, although a trailing newline is allowed.
Test IO:
#in
short array[] = {4, 3, 2, 1};

#out
short array[4];
array[0] = 4;
array[1] = 3;
array[2] = 2;
array[3] = 1;

#in
spam EGGS[] = {42};

#out
spam EGGS[1];
EGGS[0] = 42;

#in
terrible_long_type_name awful_array_name[] = {7, -8, 1337, 0, 13};

#out
terrible_long_type_name awful_array_name[5];
awful_array_name[0] = 7;
awful_array_name[1] = -8;
awful_array_name[2] = 1337;
awful_array_name[3] = 0;
awful_array_name[4] = 13;

Submissions in any language are encouraged, but bonus points if you can do it in C.
Leaderboard:
Here is a leaderboard showing the top answers:

var QUESTION_ID=77857,OVERRIDE_USER=31716;function answersUrl(e){return"https://api.stackexchange.com/2.2/questions/"+QUESTION_ID+"/answers?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}function commentUrl(e,s){return"https://api.stackexchange.com/2.2/answers/"+s.join(";")+"/comments?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+COMMENT_FILTER}function getAnswers(){jQuery.ajax({url:answersUrl(answer_page++),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){answers.push.apply(answers,e.items),answers_hash=[],answer_ids=[],e.items.forEach(function(e){e.comments=[];var s=+e.share_link.match(/\d+/);answer_ids.push(s),answers_hash[s]=e}),e.has_more||(more_answers=!1),comment_page=1,getComments()}})}function getComments(){jQuery.ajax({url:commentUrl(comment_page++,answer_ids),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){e.items.forEach(function(e){e.owner.user_id===OVERRIDE_USER&&answers_hash[e.post_id].comments.push(e)}),e.has_more?getComments():more_answers?getAnswers():process()}})}function getAuthorName(e){return e.owner.display_name}function process(){var e=[];answers.forEach(function(s){var r=s.body;s.comments.forEach(function(e){OVERRIDE_REG.test(e.body)&&(r="
"+e.body.replace(OVERRIDE_REG,"")+"
")});var a=r.match(SCORE_REG);a&&e.push({user:getAuthorName(s),size:+a[2],language:a[1],link:s.share_link})}),e.sort(function(e,s){var r=e.size,a=s.size;return r-a});var s={},r=1,a=null,n=1;e.forEach(function(e){e.size!=a&&(n=r),a=e.size,++r;var t=jQuery("#answer-template").html();t=t.replace("{{PLACE}}",n+".").replace("{{NAME}}",e.user).replace("{{LANGUAGE}}",e.language).replace("{{SIZE}}",e.size).replace("{{LINK}}",e.link),t=jQuery(t),jQuery("#answers").append(t);var o=e.language;/s.lang?1:e.lang<s.lang?-1:0});for(var c=0;c<t.length;++c){var i=jQuery("#language-template").html(),o=t[c];i=i.replace("{{LANGUAGE}}",o.lang).replace("{{NAME}}",o.user).replace("{{SIZE}}",o.size).replace("{{LINK}}",o.link),i=jQuery(i),jQuery("#languages").append(i)}}var ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe",COMMENT_FILTER="!)Q2B_A2kjfAiU78X(md6BoYk",answers=[],answers_hash,answer_ids,answer_page=1,more_answers=!0,comment_page;getAnswers();var SCORE_REG=/<h\d>\s*([^\n,]*[^\s,]),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/,OVERRIDE_REG=/^Override\s*header:\s*/i;
body{text-align:left!important}#answer-list,#language-list{padding:10px;width:290px;float:left}table thead{font-weight:700}table td{padding:5px}
 <link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b">

Leaderboard

	Author	Language	Size

Winners by Language

Language	User	Score

{{PLACE}}	{{NAME}}	{{LANGUAGE}}	{{SIZE}}	Link

{{LANGUAGE}}	{{NAME}}	{{SIZE}}	Link

Are the spaces between the array index, the equals sign, and the values required in the output? For example, would foo[0]=1; be acceptable?

@Mego That would not be acceptable. The whitespace is required. I'll edit that in.

Trailing newline allowed?

Are functions allowed?

Is it okay to return the output instead of printing it? (in case of functions)

@vaultah By default that is assumed to be okay.

Is there a maximum number of elements that need to be handled?  In particular, the current examples all have single-digit sizes, but that doesn't seem like it was intentional.

It's worth mentioning that -2147483648 is an invalid literal, so given the imput format, the valid range should be -2147483647 to 2147483647.

Can the type name contain uppercase letters?

Pyth, 44 bytes
++Khcz\]lJ:z"-?\d+"1"];"VJs[ecKd~hZ"] = "N\;

Test suite
Regular expression and string chopping. Not particularly clever.
Explanation:
++Khcz\]lJ:z"-?\d+"1"];"VJs[ecKd~hZ"] = "N\;
                                                Implicit: z = input()
    cz\]                                        Chop z on ']'
   h                                            Take string before the ']'
  K                                             Store it in K
 +                                              Add to that
         :z"-?\d+"1                             Find all numbers in the input
        J                                       Store them in J
       l                                        Take its length.
+                  "];"                         Add on "];" and print.
                       VJ                       For N in J:
                         s[                     Print the following, concatenated:
                            cKd                 Chop K on spaces.
                           e                    Take the last piece (array name)
                               ~hZ              The current interation number
                                  "] = "        That string
                                        N       The number from the input
                                         \;     And the trailing semicolon.

This answer is the thorn in my side. I thought I would be able to win it in vim, but for the life of me, I can't get the last 2-3 bytes off. =D Nice answer!

Vim, 54, 52, 49 47 keystrokes

2wa0<esc>qqYp<c-a>6ldf @qq@q$dT]dd:%norm dwf{xwC;<CR>gg"0P

Explanation:
2wa0<esc>                     'Move 2 words forward, and insert a 0.
         qq                   'Start recording in register Q
           Yp                 'Duplicate the line
             <c-a>6l          'Increment the next number then move 6 spaces right
                    df        'Delete until the next space
                       @qq@q  'Recursively call this macro

Now our buffer looks like this:
int foo[0] = {4, 8, 15, 16, 23, 42};
int foo[1] = {8, 15, 16, 23, 42};
int foo[2] = {15, 16, 23, 42};
int foo[3] = {16, 23, 42};
int foo[4] = {23, 42};
int foo[5] = {42};
int foo[6] = {42};

and our cursor is on the last line.
Second half:
$                           'Move to the end of the line
 dT]                        'Delete back until we hit a ']'
    dd                      'Delete this whole line.
      :%norm         <CR>   'Apply the following keystrokes to every line:
             dw             'Delete a word (in this case "int")
               f{x          '(f)ind the next '{', then delete it.
                  wC;       'Move a word, then (C)hange to the end of this line,
                            'and enter a ';'

Now everything looks good, we just need to add the original array-declaration. So we do:
gg        'Move to line one
  "0P     'Print buffer '0' behind us. Buffer '0' always holds the last deleted line,
          'Which in this case is "int foo[6];"

Whenever I read a vim-golf, I realise all the coding I do (mostly keyboard commands in my miscellaneous GUI editors) looks much like this, and my mind kind of bends for a minute (Vim is just turing complete (and cooler)) :P

I can't get this to work - when I type the first "@q" (of "@qq@q"), the macro runs then, and apparently runs further than it should, getting things like int foo[6] = { and ending with int foo[12 (cursor on the "2")

@LordAro I probably should have mentioned that. That's because there's already a macro in q, and that runs while you're recording, messing it up. I explained how to get around that here: http://codegolf.stackexchange.com/a/74663/31716

Hmm. OK, it now doesn't run the macro "early", but i still get the above output (runs to 12, instead of stopping at 6, which is missing anything beyond '{')

@LordAro Oh, duh, I know what's causing that. I changed df<space> to dW to save a byte, but I forgot that df<space> will break out of the macro on line 6, but dW doesn't. I'll rollback a revision. Thanks for pointing that out!

That's got it :)

While this isn't quite the shortest answer, it's by far the most impressive.

@isaacg Personally, I like this one more.

As written, this 47 has 2 problems. First, if a line has a negative number, the wC; in your :%norm deletes the number and leaves the sign. Second, you're "0Ping at the end, even though you need to paste from your dd, so you need "1P instead.

Retina, 108 104 100 69 bytes
Byte count assumes ISO 8859-1 encoding.
].+{((\S+ ?)+)
$#2];$1
+`((\w+\[).+;(\S+ )*)(-?\d+).+
$1¶$2$#3] = $4;

Beat this, PowerShell...
Code explanation
First line: ].+{((\S+ ?)+)
First, we need to keep the type, array name, and opening bracket (it saves a byte), so we don't match them. So we match the closing bracket, any number of characters, and an opening curly brace: ].+{. Then we match the number list. Shortest I've been able to find so far is this: ((\S+ ?)+). We match any number of non-space characters (this includes numbers, possible negative sign, and possible comma), followed by a space, that may or may not be there: \S+ ?. This group of characters is then repeated as many times as needed: (\S+ ?)+ and put into the large capturing group. Note that we don't match the closing curly brace or semicolon. Third line explanation tells why.
Second line: $#2];$1
Since we only matched a part of input, the unmatched parts will still be there. So we put the length of the list after the unmatched opening bracket: $#2. The replace modifier # helps us with that, as it gives us the number of matches a particular capturing group made. In this case capturing group 2. Then we put a closing bracket and a semicolon, and finally our whole list.
With input short array[] = {4, 3, 2, 1};, the internal representation after this replacing is:
short array[4];4, 3, 2, 1};
(note the closing curly brace and semicolon)
Third line: +`((\w+[).+;(\S+ )*)(-?\d+).+
This is a looped section. That means it runs until no stage in the loop makes a change to the input. First we match the array name, followed by an opening bracket: (\w+\[). Then an arbitrary number of any characters and a semicolon: .+;. Then we match the list again, but this time only numbers and the comma after each number, which have a space following them: (\S+ )*. Then we capture the last number in the list: (-?\d+) and any remaining characters behind it: .+.
Fourth line: $1¶$2$#3] = $4;
We then replace it with the array name and list followed by a newline: $1¶. Next, we put the array name, followed by the length of previously matched list, without the last element (essentially list.length - 1): $2$#3. Followed by a closing bracket and assigment operator with spaces, and this followed by the last element of our number list: ] = $4;
After first replacing, the internal representation looks like this:
short array[4];4, 3, 2,
array[3] = 1;

Note that the closing curly brace and the semicolon disappeared, thanks to the .+ at the end of third line.
After three more replacings, the internal representation looks like this:
short array[4];
array[0] = 4;
array[1] = 3;
array[2] = 2;
array[3] = 1;

Since there's nothing more to match by third line, fourth doesn't replace anything and the string is returned.
TL;DR: First we change up the int list format a bit. Then we take the last element of the list and the name, and put them after the array initialization. We do this until the int list is empty. Then we give the changed code back.
Try it online!

Someone beat me to it....:(

M!\`` and G`` are similar, but not quite the same. Be careful.

The third line explanation confuses me. The first item is the only one without a space behind it, not the last.

@CatsAreFluffy I tried changing up the wording a bit just now. What I meant was a space following a number, not preceding it. I guess I didn't fully realise the meaning of "behind". I really shouldn't write code explanations at 2 am.

@daavko "Behind" normally means "after" i.e. "following", in colloquial English. You were fine.

Ooof ... I don't think PowerShell can get down to that. Have a +1

C, 215 bytes, 196 bytes
19 bytes saved thanks to @tucuxi!
Golfed:
char i[99],o[999],b[99],z[99];t,x,n,c;main(){gets(i);sscanf(i,"%s %[^[]s",b,z);while(sscanf(i+t,"%*[^0-9]%d%n",&x,&n)==1)sprintf(o,"%s[%d] = %d;\n",z,c++,x),t+=n;printf("%s %s[%d];\n%s",b,z,c,o);}

Ungolfed:
/*
 *  Global strings:
 *   i: input string
 *   o: output string
 *   b: input array type
 *   z: input array name
*/
char i[ 99 ], o[ 999 ], b[ 99 ], z[ 99 ];

/* Global ints initialized to zeros */
t, x, n, c;

main()
{
    /* Grab input string from stdin, store into i */
    gets( i );

    /* Grab the <type> <array_name> and store into b and z */
    sscanf( i, "%s %[^[]s", b, z );

    /* Grab only the int values and concatenate to output string */
    while( sscanf( i + t, "%*[^0-9]%d%n", &x, &n ) == 1 )
    {
        /* Format the string and store into a */
        sprintf( o, "%s[%d] = %d;\n", z, c++, x );

        /* Get the current location of the pointer */
        t += n;
    }

    /* Print the <type> <array_name>[<size>]; and output string */
    printf( "%s %s[%d];\n%s", b, z, c, o );
}

Link:
http://ideone.com/h81XbI
Explanation:
To get the <type> <array_name>, the sscanf() format string is this:
%s          A string delimited by a space
    %[^[]   The character set that contains anything but a `[` symbol
         s  A string of that character set

To extract the int values from the string int foo[] = {4, 8, 15, 16, 23, 42};, I essentially tokenize the string with this function:
while( sscanf( i + t, "%*[^0-9]%d%n", &x, &n ) == 1 )

where:

i is the input string (a char*)
t is the pointer location offset of i
x is the actual int parsed from the string
n is the total characters consumed, including the found digit

The sscanf() format string means this:
%*            Ignore the following, which is..
  [^0-9]      ..anything that isn't a digit
        %d    Read and store the digit found
          %n  Store the number of characters consumed

If you visualize the input string as a char array:
int foo[] = {4, 8, 15, 16, 23, 42};
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
00000000001111111111222222222233333
01234567890123456789012345678901234

with the int 4 being located at index 13, 8 at index 16, and so on, this is what the result of each run in the loop looks like:
Run 1)  String: "int foo[] = {4, 8, 15, 16, 23, 42};"
        Starting string pointer: str[ 0 ]
        Num chars consumed until after found digit: 14
        Digit that was found: 4
        Ending string pointer: str[ 14 ]

Run 2)  String: ", 8, 15, 16, 23, 42};"
        Starting string pointer: str[ 14 ]
        Num chars consumed until after found digit: 3
        Digit that was found: 8
        Ending string pointer: str[ 17 ]

Run 3)  String: ", 15, 16, 23, 42};"
        Starting string pointer: str[ 17 ]
        Num chars consumed until after found digit: 4
        Digit that was found: 15
        Ending string pointer: str[ 21 ]

Run 4)  String: ", 16, 23, 42};"
        Starting string pointer: str[ 21 ]
        Num chars consumed until after found digit: 4
        Digit that was found: 16
        Ending string pointer: str[ 25 ]

Run 5)  String: ", 23, 42};"
        Starting string pointer: str[ 25 ]
        Num chars consumed until after found digit: 4
        Digit that was found: 23
        Ending string pointer: str[ 29 ]

Run 6)  String: ", 42};"
        Starting string pointer: str[ 29 ]
        Num chars consumed until after found digit: 4
        Digit that was found: 42
        Ending string pointer: str[ 33 ]

you can avoid using strcat by concatenating o inside sprintf, via %s. This should shave around 7 chars.

@tucuxi Ah, good catch. Thanks!

V, 37 Bytes
2Eé0òYp6ldf ò$dT]ddÎdwf{xwC;
gg"1P

V is a 2D, string based golfing language that I wrote, designed off of vim. This works as of commit 17.
Explanation:
This is pretty much a direct translation of my vim answer, albeit significantly shorter.
2E                               "Move to the end of 2 words forward.
  é0                             "Insert a single '0'
    ò       ò                    "Recursively do:
     Yp6ldf                      "Yank, paste, move 6 right, delete until space.
             $dT]                "Move to the end of line, delete backwards until ']'
                 dd              "Delete this line
                   Î             "Apply the following to every line:
                    dwf{xwC;<\n> "Delete word, move to '{' and delete it, Change to end of line, and enter ';'

Then we just have:
gg"1P     "Move to line 1, and paste buffer '1' behind us.

Since this unicode madness can be hard to enter, you can create the file with this reversible hexdump:
00000000: 3245 e930 f259 7001 366c 6466 20f2 2464  2E.0.Yp.6ldf .$d
00000010: 545d 6464 ce64 7766 7b78 7743 3b0d 6767  T]dd.dwf{xwC;.gg
00000020: 2231 500a                                "1P.

This can be run by installing V and typing:
python main.py c_array.v --f=file_with_original_text.txt

Designed off of vim. 2 notes: 1. most people says from not off of, and 2. why didn't this exist. +1

C, 195 180 bytes
195-byte original:
golfed:
char*a,*b,*c,*d;j;main(i){scanf("%ms %m[^]]%m[^;]",&a,&b,&c);
for(d=c;*d++;i+=*d==44);printf("%s %s%d];\n",a,b,i);
for(d=strtok(c,"] =,{}");j<i;j++,d=strtok(0," ,}"))printf("%s%d] = %s;\n",b,j,d);}

ungolfed:
char*a,*b,*c,*d;
j;
main(i){
    scanf("%ms %m[^]]%m[^;]",&a,&b,&c); // m-modifier does its own mallocs
    for(d=c;*d++;i+=*d==44);            // count commas
    printf("%s %s%d];\n",a,b,i);        // first line
    for(d=strtok(c,"] =,{}");j<i;j++,d=strtok(0," ,}"))
        printf("%s%d] = %s;\n",b,j,d);  // each array value
}

The two shortcuts are using the m modifier to  to get scanf's %s to allocate its own memory (saves declaring char arrays), and using strtok (which is also available by default, without includes) to do the number-parsing part.

180-byte update:
char*a,*b,*c,e[999];i;main(){scanf("%ms %m[^]]%m[^}]",&a,&b,&c);
for(c=strtok(c,"] =,{}");sprintf(e,"%s%s%d] = %s;\n",e,b,i++,c),
c=strtok(0," ,"););printf("%s %s%d];\n%s",a,b,i,e);}

ungolfed:
char*a,*b,*c,e[999];
i;
main(){
    scanf("%ms %m[^]]%m[^}]",&a,&b,&c);
    for(c=strtok(c,"] =,{}");sprintf(e,"%s%s%d] = %s;\n",e,b,i++,c),c=strtok(0," ,"););
    printf("%s %s%d];\n%s",a,b,i,e);
}

Uses bnf679's idea of appending to a string to avoid having to count commas.

Python 3.6 (pre-release), 133
m,p=str.split,print;y,u=m(input(),'[');t,n=m(y);i=m(u[5:-2],', ')
l=len(i);p(t,n+f'[{l}];')
for x in range(l):p(n+f'[{x}] = {i[x]};')

Makes heavy use of f-strings.
Ungolfed version:
y, u = input().split('[')
t, n = y.split()
i = u[5:-2].split(', ')
l = len(i)
print(t, n + f'[{l}];')
for x in range(l):
    print(n + f'[{x}] = {i[x]};')

Woah, I forgot about f-strings. Those are going to be super useful for golf!

I think you can save a byte by using a list comprehension instead of the normal loop

@someonewithpc: nope, it would actually add 1 extra byte

Ruby, 127 110 108 99 88 bytes
Anonymous function with a single argument as input. Full program, reads the input from STDIN. (If you pipe a file in, the trailing newline is optional.) Returns Prints the output string.
Took @TimmyD bragging about their solution beating all other non-esolangs as a challenge, and finally overcome the (at the time of writing) 114 byte Powershell solution they had posted. Cᴏɴᴏʀ O'Bʀɪᴇɴ's trick with splitting on ] and splicing the second half to get the numbers helped.
I need to use the splat operator more. It's so useful!
Borrowed a trick from @Neil's JavaScript ES6 answer to save more bytes by scanning for words instead of using gsub and split..
t,n,*l=gets.scan /-?\w+/;i=-1
puts t+" #{n}[#{l.size}];",l.map{|e|n+"[#{i+=1}] = #{e};"}

AFAICT the task is to write a full program.

@vaultah The default for code golf is a program or function

@Mego: the OP said "You must write a program"

@vaultah normally I would say that code golf allows me to use a function, but a full program saved me 2 bytes, so why not?

Ooof ... I don't think PowerShell can get down to that. Have a +1

Pyth - 53 50 46 45 44 bytes
2 bytes saved thanks to @FryAmTheEggman.
+Jhcz\[+`]lKcPecz\{d\;j.es[ecJd`]kd\=dPb\;)K

Test Suite.

05AB1E, 52 50 47 bytes
Code:
… = ¡`¦¨¨ð-',¡©gr¨s«„];«,®v¹ð¡¦¬s\¨N"] = "y';J,

Uses CP-1252 encoding. Try it online!.

It's gotten to the point where I skip all the other answers just looking for your 05AB1E answers. The language absolutely fascinates me.

@WorseDoughnut Thank you! That is the nicest thing someone has ever said to me about 05AB1E :)!

PowerShell v2+, 114 105 bytes
$a,$b,$c,$d=-split$args-replace'\[]';"$a $b[$(($d=-join$d|iex|iex).length)];";$d|%{"$b[$(($i++))] = $_;"}

Takes input string $args and -replaces the square bracket with nothing, then performs a -split on whitespace. We store the first bit into $a, the second bit into $b, the = into $c, and the array elements into $d. For the example below, this stores foo into $a and bar into $b, and all of the array into $d.
We then output our first line with "$a ..." and in the middle transform $d from a an array of strings of form {1,,2,,...100}; to a regular int array by -joining it together into one string, then running it through iex twice (similar to eval). We store that resultant array back in $d before calling the .length method to populate the appropriate number in between the [] in the output line.
We then send $d through a loop with |%{...}. Each iteration we output "$b..." with a counter variable $i encapsulated in brackets and the current value $_. The $i variable starts uninitialized (equivalent to $null) but the ++ will cast it to an int before the output, so it will start output at 0, all before incrementing $i for the next loop iteration.
All output lines are left on the pipeline, and output to the terminal is implicit at program termination.
Example
PS C:\Tools\Scripts\golfing> .\expand-a-c-array.ps1 "foo bar[] = {1, 2, 3, -99, 100};"
foo bar[5];
bar[0] = 1;
bar[1] = 2;
bar[2] = 3;
bar[3] = -99;
bar[4] = 100;

Whew! I managed to get my Ruby answer golfed past yours by taking your comment about beating the other non-esolangs as a challenge! Good work, though, +1.

@KevinLau Thanks! Back at ya with a 105 now. ;-)

I'll call your 105, and raise you a 99! :D

No longer closing in on beating Retina.

JavaScript (ES6), 100 bytes
(s,[t,n,...m]=s.match(/-?\w+/g))=>t+` ${n}[${m.length}];`+m.map((v,i)=>`
${n}[${i}] = ${v};`).join``

Since only the words are important, this works by just matching all the words in the original string, plus leading minus signs, then building the result. (I originally thought I was going to use replace but that turned out to be a red herring.)

[t,n,...m] almost a mystic vision

Pip, 48 47 bytes
qR`(\S+)(. = ).(.+)}`{[b#Yd^k']';.n.b.,#y.c.y]}

Takes input from stdin and prints to stdout.
Explanation
Tl;dr: Does a regex replacement, using capture groups and a callback function to construct the result.
The q special variable reads a line of input. The regex is (\S+)(. = ).(.+)}, which matches everything except the type (including trailing space) and the final semicolon. Using the first example from the question, the capturing groups get foo[, ] = , and 4, 8, 15, 16, 23, 42.
The replacement is the return value of the unnamed function {[b#Yd^k']';.n.b.,#y.c.y]}, which is called with the whole match plus the capturing groups as arguments. Thus, within the function, b gets capture group 1, c gets group 2, and d gets group 3.
We construct a list, the first three items of which will be "foo[", 6, and "]". To get the 6, we split d on the built-in variable k = ", ", Yank the resulting list of integers into the y variable for future use, and take the length (#). '] is a character literal.
What remains is to construct a series of strings of the form ";\nfoo[i] = x". To do so, we concatenate the following: ';, n (a built-in for newline), b (1st capture group), ,#y (equivalent to Python range(len(y))), c (2nd capture group), and y. Concatenation works itemwise on lists and ranges, so the result is a list of strings. Putting it all together, the return value of the function will be a list such as this:
["foo[" 6 "]"
 [";" n "foo[" 0 "] = " 4]
 [";" n "foo[" 1 "] = " 8]
 [";" n "foo[" 2 "] = " 15]
 [";" n "foo[" 3 "] = " 16]
 [";" n "foo[" 4 "] = " 23]
 [";" n "foo[" 5 "] = " 42]
]

Since this list is being used in a string Replacement, it is implicitly cast to a string. The default list-to-string conversion in Pip is concatenating all the elements:
"foo[6];
foo[0] = 4;
foo[1] = 5;
foo[2] = 15;
foo[3] = 16;
foo[4] = 23;
foo[5] = 42"

Finally, the result (including the type and the final semicolon, which weren't matched by the regex and thus remain unchanged) is auto-printed.

Perl 5.10, 73 72 68 66 + 1 (for -n switch) = 67 bytes
perl -nE '($t,$n,@a)=/[-[\w]+/g;say"$t $n".@a."];";say$n,$i++,"] = $_;"for@a'

This is a nice challenge for Perl and the shortest among general-purpose languages so far. Equivalent to
($t, $n, @a) = /[-[\w]+/g;
say "$t $n" . @a . "];";
say $n, $i++, "] = $_;" for @a;

C,278 280 bytes
golfed:
x,e,l,d;char *m,*r,*a;char i[999];c(x){return isdigit(x)||x==45;}main(){gets(i);m=r=&i;while(*r++!=32);a=r;while(*++r!=93);l=r-a;d=r-m;for(;*r++;*r==44?e++:1);printf("%.*s%d];\n",d,m,e+1);r=&i;while(*r++){if(c(*r)){m=r;while(c(*++r));printf("%.*s%d] = %.*s;\n",l,a,x++,r-m,m);}}}

ungolfed:
/* global ints
 * x = generic counter
 * e = number of elements
 * l = length of the array type
 * d = array defination upto the first '['
 */
x,e,l,d;
/* global pointers
 * m = memory pointer
 * r = memory reference / index
 * a = pointer to the start of the array type string
 */
char *m,*r,*a;
/* data storage for stdin */
char i[999];
c(x){return isdigit(x)||x=='-';}
main(){
    gets(i);
    m=r=&i;
    while(*r++!=32);                // skip first space
    a=r;
    while(*++r!=93);                // skip to ']'
    l=r-a;
    d=r-m;
    for(;*r++;*r==44?e++:1);        // count elements
    printf("%.*s%d];\n",d,m,e+1);   // print array define
    r=&i;
    while(*r++) {                   // print elements
        if(c(*r)) {                 // is char a - or a digit?
            m=r;
            while(c(*++r));         // count -/digit chars
            printf("%.*s%d] = %.*s;\n",l,a,x++,r-m,m);
        }
    }
}

While working on this someones posted a shorter version using sscanf for the parsing rather than using data pointers... nice one!
UPDATE:
Spotted missing spaces around the equals in the element printing, IDE online link:  http://ideone.com/KrgRt0 . Note this implementation does support negative numbers...

Julia, 154 134 101 bytes
f(s,c=matchall(r"-?\w+",s),n=endof(c)-2)=c[]" "c[2]"[$n];
"join([c[2]"[$i] = "c[i+3]";
"for i=0:n-1])

This is a function that accepts a string and returns a string with a single trailing newline.
Ungolfed:
function f(s, c = matchall(r"-?\w+", s), n = endof(c) - 2)
    c[] " " c[2] "[$n];\n" join([c[2] "[$i] = " x[i+3] ";\n" for i = 0:n-1])
end

We define c to be an array of matches of the input on the regular expression -?\w+. It caputres the type, array name, then each value. We store n as the length of c - 2, which is the number of values. The output is constructed as the type, name and length string interpolated, combined with each definition line separated by newlines. For whatever reason, c[] is the same as c[1].
Saved 32 bytes with help from Dennis!

JavaScript ES6, 134 132 130 129 bytes
Saved 1 byte thanks to Neil.
x=>(m=x.match(/(\w+) (\w+).+{(.+)}/),m[1]+` `+(q=m[2])+`[${q.length-1}];
`+m[3].split`, `.map((t,i)=>q+`[${i}] = ${t};`).join`
`)

Shouldn't \[${i}] = `+t+";"be`[${i}] = ${t};``?

@Neil Thanks, saved a byte!

Awk, 101 bytes
{FS="[^[:alnum:]_-]+";printf"%s %s[%d];\n",$1,$2,NF-3;for(i=3;i<NF;i++)printf$2"[%d] = %d;\n",i-3,$i}

More readably:
{
FS="[^[:alnum:]_-]+"
printf "%s %s[%d];\n", $1, $2, NF - 3
for (i=3; i < NF; i++)
    printf $2"[%d] = %d;\n", i-3, $i
}

I set the field separator to everything except alphabets, digits, the underscore and -. So, the fields would be the type name, the variable name, and the numbers.
The number of fields will be 1 (for the type) + 1 (for the name) + N (numbers) + 1 (an empty field after the trailing };). So, the size of the array is NF - 3.
Then it's just printing a special line for the declaration, and looping over the numbers.
I should assign FS either when invoking awk (using -F) or in a BEGIN block. In the interests of brevity, ….

Actually, FS must be assigned either in BEGIN or using -F otherwise it won't be used to split the first line, and since there is only 1 line of input...

@RobertBenson you're right, so the command would be awk '-F[^[:alnum:]_-]+' '{printf"%s %s[%d];\n",$1,$2,NF-3;for(i=3;i<NF;i++)printf$2"[%d] = %d;\n",i-3,$i}', which is 102 bytes not counting awk itself. Hmmm. Do I get to exclude the quotes?

Yes, you can exclude quotes. You sometimes list it as C+O bytes where C and O represent the bytes from code and options respectively. Of course I generally just use a BEGIN block, so I don't have to think about it. :p

D, 197, 188 bytes
import std.array,std.stdio;void main(){string t,n,e;readf("%s %s] = {%s}",&t,&n,&e);auto v=e.replace(",","").split;writeln(t,' ',n,v.length,"];");foreach(i,c;v)writeln(n,i,"] = ",c,";");}

or ungolfed:
import std.array, std.stdio;

void main() {
    string type, nameAndBracket, elems;
    readf("%s %s] = {%s}", &type, &nameAndBracket, &elems);

    // remove all commas before splitting the string into substrings
    auto vector = elems.replace(",","").split();

    // writeln is shorter than fln by 1 char when filled in
    writeln(type, ' ', nameAndBracket, vector.length, "];");

    // print each element being assigned
    foreach(index, content; vector)
        writeln(nameAndBraket, index, "] = ", content, ";");
}

I don't know D, but could you read the opening square bracket as part of the name? That would save you having to write a square bracket separately later.

bash, 133 129 bytes
read -a l
d="${l[@]:0:2}"
e=("${l[@]:3}")
echo "${d%?}${#e[@]}];"
for i in "${!e[@]}"
{
echo "${l[0]}[$i] = ${e[$i]//[!0-9]/};"
}

First attempt, sure its posible to get it shorter.

Python 2, 159 bytes
s=input().split()
t,n,v=s[0],s[1][:-2],''.join(s[3:])
a=v[1:-2].split(',')
print'%s %s[%d];'%(t,n,len(a))
for i in range(len(a)):print'%s[%d] = %s;'%(n,i,a[i])

Try it online
Thanks Kevin Lau for some golfing suggestions

Python 3, 116 bytes
t,v,_,*l=input().split();v=v[:-1]+'%s]'
print(t,v%len(l)+';');i=0
for x in l:print(v%i,'= %s;'%x.strip('{,};'));i+=1

Splits the input into the type, name, and the list of numbers. After printing the array declaring, prints the elements by manually enumerating through the numbers, removing excess punctuation that attached to the first and last one.
A different approach in Python 2 came out to 122 bytes:
a,b=input()[:-2].split('] = {')
l=eval(b+',')
print a+`len(l)`+"];"
for y in enumerate(l):print a.split()[1]+'%s] = %s;'%y

The idea is to eval the list of numbers as a tuple, with a comma at the end so that a single number is recognized as a type. The enumerated list of numbers provides tuples to string-format in.

PHP, 143 bytes
Golfed
<?$t=count($n=explode(' ',preg_replace('/[^\s\w]/','',$argv[1])))-3;echo"$n[0] {$n[1]}[$t];";for($i=2;$t>$j=++$i-3;)echo$n[1]."[$j] = $n[$i];";

Ungolfed
<?
$t = count(                                  // Get the number of elements for our array...
    $n = explode(' ',                            // After split the input on whitespace...
    preg_replace('/[^\s\w]/','',$argv[1])))-3;  // After removing all special characters.
echo "$n[0] {$n[1]}[$t];";                     // First line is type, name, and count.
for($i=2;                                        // Loop through array elements
    $t > $j = ++$i-3;)                         // Assign j to be the actual index for our new array
    echo $n[1]."[$j] = $n[$i];";                // Print each line

Input is taken through command line argument. Sample:
C:\(filepath)>php Expand.php "int foo[] = {4,8,15,16,23,42};"

Output:
int foo[6];foo[0] = 4;foo[1] = 8;foo[2] = 15;foo[3] = 16;foo[4] = 23;foo[5] = 42;

MATL, 68 64 58 bytes
'\w+'XX2:H#)XKxXIZc'['KnV'];'v!K"I2X)'['X@qV'] = '@g';'6$h

This isn't C, but it does use C-like sprintf function Nah, that was wasting 4 bytes.
Try it online!
          % Take input implicitly
'\w+'XX   % Find substrings that match regex '\w+'. Gives a cell array
2:H#)     % Split into a subarray with the first two substrings (type and name), and
          % another with the rest (numbers that form the array)
XKx       % Copy the latter (numbers) into clipboard K. Delete it
XI        % Copy the former (type and name) into clipboard I
Zc        % Join the first two substrings with a space
'['       % Push this string
K         % Paste array of numbers
nV        % Get its length. Convert to string
'];'      % Push this string
v!        % Concatenate all strings up to now. Gives first line of the output
K"        % For each number in the array
  I2X)    %   Get name of array as a string
  '['     %   Push this string
  X@qV    %   Current iteration index, starting at 0, as a string
  '] = '  %   Push this string
  @g      %   Current number of the array, as a string
  ';'     %   Push this string
  5$h     %   Concatenate top 6 strings. This is a line of the output
          % Implicity end for each
          % Implicitly display

Clojure, 115 bytes
#(let[[t n & v](re-seq #"-?\w+"%)](apply str t" "n\[(count v)"];\n"(map(fn[i v](str n"["i"] = "v";\n"))(range)v))))

I wasn't able to nicely merge awful_array_name[5]; and awful_array_name[0] = 7; parts so that they'd re-use code :/

source: Stack Exchange

license: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/

sort: votes