Bubble sort
Bubble sort is very easy to understand, use two for loop to sort the array, and the time complexity is O(n2).
Bubble Sort is the simplest sorting algorithm that works by repeatedly swapping the adjacent elements if they are in wrong order.
public class Study {
/**
* main function to sort array using bubble sort
*
* @param args
*/
public static void main(String[] args) {
int[] arr = {1, -10, -2, 3, 8, 100, -100, 2, 6, 25};
print(arr);
System.out.println();
bubbleAsc(arr);
// bubbleDes(arr);
print(arr);
}
/**
* ascending order
*
* @param arr
*/
private static void bubbleAsc(int[] arr) {
// flag is used to mark whether swap happens in one single bubble i from 0 to lastUnsortedIndex
boolean flag = false;
// lastUnsortedIndex means the last index of the unsorted array, the original value is arr.length-1
// since the input array is unsorted at beginning
for (int lastUnsortedIndex = arr.length - 1; lastUnsortedIndex > 0; lastUnsortedIndex--) {
// each bubble loop we sort i from 0 to lastUnsortedIndex
for (int i = 0; i < lastUnsortedIndex; i++) {
if (arr[i] > arr[i + 1]) {
swap(arr, i, i + 1);
flag = true;
}
}
if(!flag) break;
}
}
/**
* descending order
*
* @param arr
*/
private static void bubbleDes(int[] arr) {
// flag is used to mark whether swap happens in one single bubble i from 0 to lastUnsortedIndex
boolean flag = false;
for (int lastUnsortedIndex = arr.length - 1; lastUnsortedIndex > 0; lastUnsortedIndex--) {
for (int i = 0; i < lastUnsortedIndex; i++) {
if (arr[i] < arr[i + 1]) {
swap(arr, i, i + 1);
}
}
}
}
/**
* swap values
*
* @param arr
* @param i
* @param j
*/
private static void swap(int[] arr, int i, int j) {
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
/**
* print the array
*
* @param arr
*/
private static void print(int[] arr) {
for (int i = 0; i < arr.length; i++) {
System.out.print("arr[" + i + "] = " + arr[i] + " ");
}
}
}
Result
arr[0] = 1 arr[1] = -10 arr[2] = -2 arr[3] = 3 arr[4] = 8 arr[5] = 100 arr[6] = -100 arr[7] = 2 arr[8] = 6 arr[9] = 25
arr[0] = 100 arr[1] = 25 arr[2] = 8 arr[3] = 6 arr[4] = 3 arr[5] = 2 arr[6] = 1 arr[7] = -2 arr[8] = -10 arr[9] = -100