Rectifying Bubble Sort logic, introducing modification, removing code inconsistency (#30274)

* Update to index.md + code fix

Before this commit, the js and c++ versions of the code had the O(n) modification with the flag but the Java, Python, Swift ones did not. Also, Bubble sort is originally O(n^2) for all cases and the flag is a modification to it, as far as I know. I updated the code to reflect the same in the first section, and added a new section explaining the modification with examples in 3 languages. Hope this is alright.

* fix: corrected code block syntax
This commit is contained in:
Ronit Ray
2019-06-28 03:09:47 +05:30
committed by Randell Dawson
parent 3e175e52b3
commit 0213ee1a13

View File

@@ -43,7 +43,7 @@ Now, the array is already sorted, but our algorithm does not know if it is compl
#### Properties
- Space complexity: O(1)
- Best case performance: O(n)
- Best case performance: O(n\*n)
- Average case performance: O(n\*n)
- Worst case performance: O(n\*n)
- Stable: Yes
@@ -51,8 +51,84 @@ 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)
### Example in Java.
```java
public int[] bubSort(int []ar)
{
int i, j, temp;
for (i = 0; i < n; i++)
{
for (j = 0; j < n - 1 - i; j++)
{
if (ar[j] > ar[j+1])
{
temp = ar[j];
ar[j] = ar[j + 1];
ar[j + 1] = temp;
}
}
}
return ar[];
}
```
### Example in C++
```cpp
#include <iostream>
using namespace std;
int BubbleSort[] (int arr[], int n)
{
int i, j, temp;
for (i = 0; i < n; ++i)
{
for (j = 0; j < n-i-1; ++j)
{
if (arr[j] > arr[j+1])
{
temp = arr[j]
arr[j] = arr[j+1];
arr[j+1] = temp;
}
}
}
return arr;
}
```
### 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
}
```
### Example in Python
```python
def bubblesort( A ):
for i in range( len( A ) ):
for k in range( len( A ) - 1, i, -1 ):
if ( A[k] < A[k - 1] ):
swap( A, k, k - 1 )
def swap( A, x, y ):
tmp = A[x]
A[x] = A[y]
A[y] = tmp
```
### Modified Bubble Sort
We now know that Bubble Sort has a general complexity of O(n^2) for all input cases. Since this is a very slow sort, one of the commonly-suggested and fairly easy optimizations can be made to include the best case (where the list/array provided as input is already sorted). If we are able to check this condition (by making N comparisons), we should be able to terminate execution immediately after validating the fact that the array is sorted.
This means that in the best case, our modified Bubble Sort Algorithm would have a complexity of O(n). This doesn't change the average or worst case, of course, but may show a decent uptick in speed if you intend to sort a number of instances, some of which are likely to be sorted already.
### Example in JavaScript
```js
let arr = [1, 4, 7, 45, 7,43, 44, 25, 6, 4, 6, 9],
sorted = false;
@@ -70,42 +146,32 @@ while(!sorted) {
}
```
### Example in Java.
```java
public class BubbleSort {
static void sort(int[] arr) {
int n = arr.length;
int temp = 0;
for(int i=0; i < n; i++){
for(int x=1; x < (n-i); x++){
if(arr[x-1] > arr[x]){
temp = arr[x-1];
arr[x-1] = arr[x];
arr[x] = temp;
}
public int[] bubSortModified(int []ar)
{
int i, j, temp;
boolean sorted;
for (i = 0; i < n; i++)
{
sorted = true;
for (j = 0; j < n - 1 - i; j++)
{
if (ar[j] > ar[j+1])
{
sorted = false; //implying array was not sorted already, swaps are needed
temp = ar[j];
ar[j] = ar[j + 1];
ar[j + 1] = temp;
}
}
}
public static void main(String[] args) {
for(int i=0; i < 15; i++){
int arr[i] = (int)(Math.random() * 100 + 1);
}
System.out.println("array before sorting\n");
for(int i=0; i < arr.length; i++){
System.out.print(arr[i] + " ");
}
bubbleSort(arr);
System.out.println("\n array after sorting\n");
for(int i=0; i < arr.length; i++){
System.out.print(arr[i] + " ");
}
if (sorted == true)
break; //if array is sorted, stop iterating
}
return ar[];
}
```
### Example in C++
```cpp
// Recursive Implementation
@@ -130,33 +196,6 @@ 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
}
```
### Example in Python
```py
def bubbleSort(arr):
n = len(arr)
for i in range(n):
for j in range(0, n-i-1):
if arr[j] > arr[j+1] :
arr[j], arr[j+1] = arr[j+1], arr[j]
print(arr)
```
### Example in Ruby
```ruby