The Bubble sort algorithm is one of the simplest sorting algorithms, but it is also one of the most inefficient for large data sets because it does not take advantage of any form of caching or parallelism.

It is used by starting at the beginning of an array and comparing the first couple of elements. The elements are only swapped if the first element has a greater value than the second element. This process of comparing adjacent elements continues throughout the array until no swaps are necessary or the whole array got sorted.

Psuedo Code:

@function start
function bubblesort( arr ) // parameter arr is an array
   variable n = arr.length
    Iterate i from 1 to n
        Iterate J from 0 to n - 1
           if arr[j] > arr[j + 1]
              swap( arr[j], arr[j + 1] )
@function end

Swift code to perform bubble sort:

var arr: [Int] = [10, 5, 89, 26]

func bubblesort(arr: [Int]) -> [Int] {

var array = arr

    for i in 0..<array.count {

      for j in 1..<array.count – i {

        if array[j] < array[j-1] {

          let tmp = array[j-1]

          array[j-1] = array[j]

          array[j] = tmp

        }

      }

    }

    return array

}

bubblesort(arr: arr)

Bubble sort using Array.swatAt method,

var arr: [Int] = [10, 5, 89, 26]

func bubblesort(arr: [Int]) -> [Int] {

var array = arr

    for i in 0..<array.count {

      for j in 1..<array.count – i {

        if array[j] < array[j-1] {

          array.swapAt(j, j+1)

        }

      }

    }

    return array

}

bubblesort(arr: arr)

0 Comments

Submit a Comment

Your email address will not be published. Required fields are marked *