sort.carbon 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. // Part of the Carbon Language project, under the Apache License v2.0 with LLVM
  2. // Exceptions. See /LICENSE for license information.
  3. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  4. library "sort";
  5. // TODO: Generalize this for other container types once we implement lowering
  6. // for generic functions.
  7. fn Swap(p: [i32; 1000]*, from: i32, to: i32) {
  8. var tmp: i32 = (*p)[from];
  9. (*p)[from] = (*p)[to];
  10. (*p)[to] = tmp;
  11. }
  12. fn Partition(p: [i32; 1000]*, from_in: i32, to_in: i32) -> i32 {
  13. var pivot_index: i32 = from_in;
  14. var pivot: i32 = (*p)[pivot_index];
  15. var from: i32 = from_in + 1;
  16. var to: i32 = to_in;
  17. while (from < to) {
  18. if ((*p)[from] <= pivot) {
  19. ++from;
  20. } else if ((*p)[to - 1] > pivot) {
  21. --to;
  22. } else {
  23. // Element at `from` is > pivot, and
  24. // element at `to` is <= pivot.
  25. Swap(p, from, to - 1);
  26. ++from;
  27. --to;
  28. }
  29. }
  30. Swap(p, pivot_index, from - 1);
  31. return from - 1;
  32. }
  33. fn Quicksort(p: [i32; 1000]*, from: i32, to: i32) {
  34. if (from + 1 >= to) { return; }
  35. var pivot: i32 = Partition(p, from, to);
  36. Quicksort(p, from, pivot);
  37. Quicksort(p, pivot + 1, to);
  38. }