Created
December 6, 2020 12:01
-
-
Save mahmmoudkinawy/a8ef941fd534417df419e98c7edabb2b to your computer and use it in GitHub Desktop.
Bubble Sort With Java
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 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