How to resolve the algorithm Sorting algorithms/Bubble sort step by step in the Nim programming language

Published on 12 May 2024 09:40 PM

How to resolve the algorithm Sorting algorithms/Bubble sort step by step in the Nim programming language

Table of Contents

Problem Statement

A   bubble   sort is generally considered to be the simplest sorting algorithm. A   bubble   sort is also known as a   sinking   sort. Because of its simplicity and ease of visualization, it is often taught in introductory computer science courses. Because of its abysmal O(n2) performance, it is not used often for large (or even medium-sized) datasets. The bubble sort works by passing sequentially over a list, comparing each value to the one immediately after it.   If the first value is greater than the second, their positions are switched.   Over a number of passes, at most equal to the number of elements in the list, all of the values drift into their correct positions (large values "bubble" rapidly toward the end, pushing others down around them).  
Because each pass finds the maximum item and puts it at the end, the portion of the list to be sorted can be reduced at each pass.   A boolean variable is used to track whether any changes have been made in the current pass; when a pass completes without changing anything, the algorithm exits. This can be expressed in pseudo-code as follows (assuming 1-based indexing):

Sort an array of elements using the bubble sort algorithm.   The elements must have a total order and the index of the array can be of any discrete type.   For languages where this is not possible, sort an array of integers.

Let's start with the solution:

Step by Step solution about How to resolve the algorithm Sorting algorithms/Bubble sort step by step in the Nim programming language

Source code in the nim programming language

proc bubbleSort[T](a: var openarray[T]) =
  var t = true
  for n in countdown(a.len-2, 0):
    if not t: break
    t = false
    for j in 0..n:
      if a[j] <= a[j+1]: continue
      swap a[j], a[j+1]
      t = true

var a = @[4, 65, 2, -31, 0, 99, 2, 83, 782]
bubbleSort a
echo a


  

You may also check:How to resolve the algorithm Luhn test of credit card numbers step by step in the Logo programming language
You may also check:How to resolve the algorithm Identity matrix step by step in the AppleScript programming language
You may also check:How to resolve the algorithm Check output device is a terminal step by step in the Python programming language
You may also check:How to resolve the algorithm Colour bars/Display step by step in the R programming language
You may also check:How to resolve the algorithm Bitwise operations step by step in the AWK programming language