diff options
| author | Cliff Click <cliffc@acm.org> | 2026-08-10 11:11:18 -0700 |
|---|---|---|
| committer | Cliff Click <cliffc@acm.org> | 2026-08-10 15:21:17 -0700 |
| commit | 28209703c72fb7e9955961dbdb84e24a0f871acd (patch) | |
| tree | 8e4df2c1a5e6811696b454bbc4d7cd1cc30e42e7 /docs/chapter25/examples/BubbleSort.smp | |
| parent | e57bdd315a7918a0d130e1c95648ca4a1b4f08ed (diff) | |
| download | Simple-linear-chapter25.tar.gz Simple-linear-chapter25.zip | |
Chapter 25: Moduleslinear-chapter25
Diffstat (limited to 'docs/chapter25/examples/BubbleSort.smp')
| -rw-r--r-- | docs/chapter25/examples/BubbleSort.smp | 33 |
1 files changed, 33 insertions, 0 deletions
diff --git a/docs/chapter25/examples/BubbleSort.smp b/docs/chapter25/examples/BubbleSort.smp new file mode 100644 index 00000000..864e26da --- /dev/null +++ b/docs/chapter25/examples/BubbleSort.smp @@ -0,0 +1,33 @@ +// -*- mode: java; -*- + +// An implementation of +// https://sampleprograms.io/projects/bubble-sort/ +// +// Bubble sort, with reading (parsing) and writing (formatting) the data. + +val sort = { sys.aryi64 nums -> + var done = false; + while( !done ) { + done = true; + for( var i = 0; i < nums.len-1; i++ ) + if( nums.buf[i] > nums.buf[i+1] ) { + nums.swap(i,i+1); + done = false; + } + } +}; + +// Read from stdin a line of the form "[ 4, 3, 2, 1]" and print it sorted. +val main = { -> + // Parse array of numbers from stdin + var nums = sys.aryi64.parseAryI64( sys.io.stdin() ); + if( !nums ) + return sys.io.p("stdin must look like [4, 3, 2, 1]"); + + // Bubble sort array of integers + sort(nums); + + // Print a list of numbers to stdout + nums.str().write(1); + return 0; +}; |
