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] {

vararray = arr

foriin0..<array.count {

forjin1..<array.count – i {

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

lettmp = array[j-1]array[j-1] = array[j]

array[j] = tmp

}

}

}

returnarray}

bubblesort(arr: arr)

var arr: [Int] = [10, 5, 89, 26] func bubblesort(arr: [Int]) -> [Int] {

vararray = arr

foriin0..<array.count {

forjin1..<array.count – i {

ifarray[j] < array[j-1] {array.swapAt(j, j+1)

}

}

}

returnarray}

bubblesort(arr: arr)

## 0 Comments