Created
September 14, 2018 09:50
-
-
Save nivdul/24bd1623b1ee7632660e600fe3a187fc to your computer and use it in GitHub Desktop.
BubbleSortSwapExample
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class BubbleSortSwap { | |
/** | |
* Swap two elements indexed by a and b in an array | |
*/ | |
static void swap(int[] arr, int a, int b) { | |
int temp = arr[a]; | |
arr[a] = arr[b]; | |
arr[b] = temp; | |
} | |
/** | |
* BubbleSort | |
* Sort an array from the lowest item to the higher item | |
* | |
* Comment on algorithm: | |
* - The main iteration walks through the array | |
* - For each index value i, an inner iteration walks through from upper | |
* limit to index | |
* - At each iteration, the lighter element is sent to the lowest index | |
* | |
* This a the reason why this algorithm is called bubble sort | |
*/ | |
public static int[] bubbleSort(int[] arr, int n) { | |
for (int i = 0; i < n; i++) { | |
for (int j = n - 1 ; j > i; j--) { | |
if (arr[j-1] > arr[j]) { | |
swap(arr, j,j-1); | |
} | |
} | |
} | |
return arr; | |
}; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment