Skip to content

Instantly share code, notes, and snippets.

@nivdul
Created September 14, 2018 09:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nivdul/24bd1623b1ee7632660e600fe3a187fc to your computer and use it in GitHub Desktop.
Save nivdul/24bd1623b1ee7632660e600fe3a187fc to your computer and use it in GitHub Desktop.
BubbleSortSwapExample
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