Skip to content

Instantly share code, notes, and snippets.

@mahmmoudkinawy
Created December 6, 2020 12:01
Show Gist options
  • Save mahmmoudkinawy/a8ef941fd534417df419e98c7edabb2b to your computer and use it in GitHub Desktop.
Save mahmmoudkinawy/a8ef941fd534417df419e98c7edabb2b to your computer and use it in GitHub Desktop.
Bubble Sort With Java
public static void swap(int[] arr, int index1, int index2) {
int temp = arr[index1];
arr[index1] = arr[index2];
arr[index2] = temp;
}
public static void bubbleSort(int[] arr) {
for (int i = 0; i < arr.length; i++) {
for (int j = 1; j < arr.length; j++) {
if (arr[j] < arr[j - 1]) {
swap(arr, j, j - 1);
}
}
}
}
public static void main(String[] args) {
int[] arr = {-5,1,2,6,9,-99};
System.out.println("Before sort : ");
for (int i = 0; i < arr.length; i++) {
System.out.print(arr[i] + " ");
}
System.out.println();
bubbleSort(arr);
System.out.println("After sort : ");
for (int i = 0; i < arr.length; i++) {
System.out.print(arr[i] + " ");
}
System.out.println();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment