public class BubbleSort {
public static void main(String[] args) {
int values[] = { 5, 4, 8, 6, 9, 1, 7, 3, 2 };
System.out.print("\nBefore sort : ");
printArray(values);
bubbleSort(values);
System.out.print("\nAfter sort : ");
printArray(values);
}
private static void bubbleSort(int[] array) {
for (int i = 0; i < array.length - 1; i++) {
for (int j = i + 1; j < array.length; j++) {
if (array[i] > array[j]) {
int tmp = array[i];
array[i] = array[j];
array[j] = tmp;
}
}
}
}
private static void printArray(int[] array) {
for (int i = 0; i < array.length; i++) {
System.out.print(array[i] + ", ");
}
}
}
OUTPUT:
Before sort : 5, 4, 8, 6, 9, 1, 7, 3, 2,
After sort : 1, 2, 3, 4, 5, 6, 7, 8, 9,
No comments:
Write comments