From d1f8e52eba295f4afe68f6b1b4d4e094fcc3b885 Mon Sep 17 00:00:00 2001 From: damirka Date: Mon, 5 Jul 2021 16:28:50 +0300 Subject: [PATCH] rework example to shaker sort --- docs/rfc/005-countdown-loops.md | 53 ++++++++++++++++++++++++++++----- 1 file changed, 45 insertions(+), 8 deletions(-) diff --git a/docs/rfc/005-countdown-loops.md b/docs/rfc/005-countdown-loops.md index a2d785a512..a1391a35d8 100644 --- a/docs/rfc/005-countdown-loops.md +++ b/docs/rfc/005-countdown-loops.md @@ -23,16 +23,25 @@ This proposal suggests adding countdown loops and inclusive loop ranges into Leo In the current design of the language only incremental ranges are allowed. Though in some cases there's a need for loops going in the reverse direction. This example -demonstrates the bubble sort algorithm where countdown loops are mocked: +demonstrates the shaker sort algorithm where countdown loops are mocked: ```ts -function bubble_sort(a: [u32; 10]) -> [u32; 10] { - for i in 0..9 { // i counts up - for j in 0..9-i { // i is flipped - if (a[j] > a[j+1]) { - let tmp = a[j]; - a[j] = a[j+1]; - a[j+1] = tmp; +function shaker_sort(a: [u32; 10], const rounds: u32) -> [u32; 10] { + for k in 0..rounds { + for i in 0..9 { + if a[i] > a[i + 1] { + let tmp = a[i]; + a[i] = a[i + 1]; + a[i + 1] = tmp; + } + + } + for j in 0..9 { // j goes from 0 to 8 + let i = 8 - j; // j is flipped + if a[i] > a[i + 1] { + let tmp = a[i]; + a[i] = a[i + 1]; + a[i + 1] = tmp; } } } @@ -85,6 +94,34 @@ for i in 0..5 {} for i in 0..=5 {} ``` +## Example + +The code example demostrated in the Motivation part of this document +could be extended (or simplified) with suggested syntax: + +```ts +function shaker_sort(a: [u32; 10], const rounds: u32) -> [u32; 10] { + for k in 0..rounds { + for i in 0..9 { // i goes from 0 to 8 + if a[i] > a[i + 1] { + let tmp = a[i]; + a[i] = a[i + 1]; + a[i + 1] = tmp; + } + + } + for i in 8..=0 { // j goes from 8 to 0 + if a[i] > a[i + 1] { + let tmp = a[i]; + a[i] = a[i + 1]; + a[i + 1] = tmp; + } + } + } + return a; +} +``` + # Drawbacks -