Skip to content
This repository has been archived by the owner on Oct 22, 2021. It is now read-only.

add bubble sort algorithm using swift #78

Merged
merged 7 commits into from
Oct 20, 2021
Merged
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 19 additions & 8 deletions Sorting Algorithms/Bubble Sort/BubbleSort.swift
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
//
// BubbleSort.swift
//
//
//
// Created by Pubudu Mihiranga on 19/10/21.
//
Expand All @@ -11,16 +11,26 @@ import Foundation

func bubbleSort(_ dataArray: [Int]) -> [Int] {
var unsortedArray = dataArray
pubudu-m marked this conversation as resolved.
Show resolved Hide resolved
pubudu-m marked this conversation as resolved.
Show resolved Hide resolved
for _ in 0...unsortedArray.count {
for value in 1...unsortedArray.count - 1 {
if unsortedArray[value-1] > unsortedArray[value] {
let tempValue = unsortedArray[value-1]
unsortedArray[value-1] = unsortedArray[value]
unsortedArray[value] = tempValue

if unsortedArray.count <= 1 {
pubudu-m marked this conversation as resolved.
Show resolved Hide resolved
return dataArray
}

let lastPosition = unsortedArray.count - 1
var shouldSwap = true

while shouldSwap {
shouldSwap = false
for i in 1...lastPosition {
if unsortedArray[i-1] > unsortedArray[i] {
let tempValue = unsortedArray[i-1]
unsortedArray[i-1] = unsortedArray[i]
unsortedArray[i] = tempValue
shouldSwap = true
}
}
}

return unsortedArray
}

Expand All @@ -31,3 +41,4 @@ print("Unsorted := \(dataArray)") //output := Unsorted := [3, 4, 5, 1, 0, 8, 1]

let sortedArray = bubbleSort(dataArray)
print("Sorted := \(sortedArray)") //output := Sorted := [0, 1, 1, 3, 4, 5, 8]