From 8fd54d9d482ae253c4c46a67dcc80cb98665cecb Mon Sep 17 00:00:00 2001 From: Marwan Alani Date: Sun, 14 Oct 2018 20:36:28 -0400 Subject: [PATCH] feat(guide): Add example of Bubble Sort in Swift --- .../sorting-algorithms/bubble-sort/index.md | 35 +++++++++++-------- 1 file changed, 21 insertions(+), 14 deletions(-) diff --git a/client/src/pages/guide/english/algorithms/sorting-algorithms/bubble-sort/index.md b/client/src/pages/guide/english/algorithms/sorting-algorithms/bubble-sort/index.md index 62b8484fc0..eafa8636cb 100644 --- a/client/src/pages/guide/english/algorithms/sorting-algorithms/bubble-sort/index.md +++ b/client/src/pages/guide/english/algorithms/sorting-algorithms/bubble-sort/index.md @@ -51,7 +51,9 @@ Now, the array is already sorted, but our algorithm does not know if it is compl ### Video Explanation [Bubble sort in easy way](https://www.youtube.com/watch?v=Jdtq5uKz-w4) -This code will use bubble sort to sort the array. +----- + +### Example in JavaScript ```js let arr = [1, 4, 7, 45, 7,43, 44, 25, 6, 4, 6, 9]; let sorted = false @@ -68,16 +70,7 @@ while(!sorted) { } } ``` - -### Properties: -* Space Complexity: O(1) -* Time Complexity: O(n), O(n* n), O(n* n) for Best, Average and Worst cases respectively. -* In place: Yes -* Stable: Yes - -======= -Here is the algorithm written in Java. - +### Example in Java. ```java public class bubble-sort { static void sort(int[] arr) { @@ -114,10 +107,9 @@ public class bubble-sort { } } ``` -======= -###The Recursive implementation of the Bubble Sort. - +### Example in C++ ```c++ +// Recursive Implementation void bubblesort(int arr[], int n) { if(n==1) //Initial Case @@ -136,6 +128,21 @@ void bubblesort(int arr[], int n) bubblesort(arr,n-1); //Recursion for remaining array } ``` +### Example in Swift +```swift +func bubbleSort(_ inputArray: [Int]) -> [Int] { + guard inputArray.count > 1 else { return inputArray } // make sure our input array has more than 1 element + var numbers = inputArray // function arguments are constant by default in Swift, so we make a copy + for i in 0..<(numbers.count - 1) { + for j in 0..<(numbers.count - i - 1) { + if numbers[j] > numbers[j + 1] { + numbers.swapAt(j, j + 1) + } + } + } + return numbers // return the sorted array +} +``` ### More Information - [Wikipedia](https://en.wikipedia.org/wiki/Bubble_sort)