# Swift Program to sort an array in ascending order using bubble sort

In swift, Bubble sort algorithm is the easiest search algorithm. This algorithm sorts the elements by repeatedly swapping adjacent elements if they are not present at the right place. So now we sort an array in ascending order using bubble sort.

For example âˆ’

Array - [4, 7, 1, 8]

• 1st iteration âˆ’ compare two elements, if the first element is greater than second element then swap their position. If not, then move to next pair.

[4, 7, 1, 8] 4<7, remain same
[4, 7, 1, 8] 7>1, swap the position
[4, 1, 7, 8] 7<8, remain same

• 2nd iteration âˆ’ Again compare two elements and swap their position if first element is greater than second element.

[4, 1, 7, 8] 4>1, swap the position
[1, 4, 7, 8] 4<7, remain same
[1, 4, 7, 8] 7<8, remain same
So the sorted array in ascending order is [1, 4, 7, 8]


## Algorithm

• Step 1 âˆ’ Create a function to sort the array in ascending order using bubble sort algorithm.

• Step 2 âˆ’ Inside the function, we run nested for-in loop to traverse over each pair of adjacent element in the given.

• Step 3 âˆ’ Check if array[y]>array[y+1]. If yes, then swap the position of the elements without each other. If no, then move to next pair.

• Step 4 âˆ’ Now outside the function create an array of integer type.

• Step 5 âˆ’ Call the function and pass the array into it.

• Step 6 âˆ’ Print the sorted array.

## Example

In the following example, we will create a function named as mBubbleSort(). This function takes an array as input and sorts the given array into ascending order with the help of the bubble sort algorithm. This function uses a nested for-in loop to iterate through each pair of an adjacent element the given array and swap if the first element is greater than the second element. This process continues till the last unsorted element. Here the function modifies the original array with the help of inout parameter. Finally, display the sorted array.

import Foundation
import Glibc

// Function to sort array in ascending order using bubble sort
func mBubbleSort(_ array: inout [Int]) {
let size = array.count

for x in 0..<size {
for y in 0..<size-x-1 {

if array[y] > array[y+1] {
// Swap the elements if they are
// not in the correct order
let temp = array[y]
array[y] = array[y+1]
array[y+1] = temp
}
}
}
}

// Array of integer type
var arr = [56, 2, 89, 3, 87, 22, 1, 6, 4]
mBubbleSort(&arr)
print("Sorted array in ascending order: \(arr)")


## Output

Sorted array in ascending order: [1, 2, 3, 4, 6, 22, 56, 87, 89]


## Conclusion

So this is how we can sort an array in ascending order using bubble sort.This algorithm works well only for small set of elements, it is not suitable for larger number of elements because its average and worst case time complexity is high.

Updated on: 24-Apr-2023

526 Views 