Bubble sort : In bubble sort ,we will select the 1st element and compare with all the remaining element, same process we will continue for all the elements as we are traveling the whole Array 2 times except the element which we have selected to compare with other elements but still it will be consider as n time.
So time complexity for bubble sort will be O(n^2).
space complexity for bubble sort will be O(1).
So time complexity for bubble sort will be O(n^2).
space complexity for bubble sort will be O(1).
// Bubble Sort
class BubbleSort {
public static void sort(int[] array) {
int n = array.length;
while (true) {
boolean swapped = false;
for (int i = 0; i < n - 1; i++) {
if (array[i + 1] < array[i]) {
swap(array, i, i + 1);
swapped = true;
}
}
if (!swapped) break;
}
}
private static void swap(int[] array, int i, int j) {
int temp = array[i];
array[i] = array[j];
array[j] = temp;
}
private static void print(int[] A) {
System.out.print("[");
for (int i = 0; i < A.length; i++) {
System.out.print(A[i]);
if (i < A.length - 1) {
System.out.print(", ");
}
}
System.out.println("]");
}
public static void main(String[] args) {
int[] A = {111, 80, 14, 21, 19, 31, 19, 121, 10, 190, 80, 6, 7};
sort(A);
print(A);
}
}
Please have a look to the source code of all sorting method from below link
Comments
Post a Comment