Files
carbon-lang/examples/advent2024/sort.carbon
T
Dana Jansensandzygoloid 24bde46181 Change array syntax from [T; N] to array(T, N) (#4981)
In line with the proposal in #4682, this changes the array syntax to be
array(T, N). `array` is a builtin keyword which must be followed by
parens containing two expressions and a separating comma.

The array type expression is still fully builtin, it does not forward to
a Core.Array library type yet. It merely adds the `ArrayType`
instruction, as was done with the previous syntax.

Followup work will change the instruction to reference to Core.Array,
once the library type exists and can be used directly.

---------

Co-authored-by: zygoloid <richard@metafoo.co.uk>
2025-02-20 22:42:47 +00:00

44 lines
1.1 KiB
Plaintext

// Part of the Carbon Language project, under the Apache License v2.0 with LLVM
// Exceptions. See /LICENSE for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
library "sort";
// TODO: Generalize this for other container types once we implement lowering
// for generic functions.
fn Swap(p: array(i32, 1000)*, from: i32, to: i32) {
var tmp: i32 = (*p)[from];
(*p)[from] = (*p)[to];
(*p)[to] = tmp;
}
fn Partition(p: array(i32, 1000)*, from_in: i32, to_in: i32) -> i32 {
var pivot_index: i32 = from_in;
var pivot: i32 = (*p)[pivot_index];
var from: i32 = from_in + 1;
var to: i32 = to_in;
while (from < to) {
if ((*p)[from] <= pivot) {
++from;
} else if ((*p)[to - 1] > pivot) {
--to;
} else {
// Element at `from` is > pivot, and
// element at `to` is <= pivot.
Swap(p, from, to - 1);
++from;
--to;
}
}
Swap(p, pivot_index, from - 1);
return from - 1;
}
fn Quicksort(p: array(i32, 1000)*, from: i32, to: i32) {
if (from + 1 >= to) { return; }
var pivot: i32 = Partition(p, from, to);
Quicksort(p, from, pivot);
Quicksort(p, pivot + 1, to);
}