// Bubble sort algorithm in increasing order:
// Bubble sort algorithm in decreasing order:
- public class BubbleSortAlgorithm {
- public static void main(String[] args) {
- int a[] = { 3, 4, 5, 43, 2, 2, 45, 66, 5, 4, 32 };
- int temp;
- for (int i = 0; i < a.length; i++) {
- for (int j = 0; j < a.length-1; j++) {
- if (a[j] > a[j + 1]) {
- temp = a[j];
- a[j] = a[j + 1];
- a[j + 1] = temp;
- }
- }
- }
- for (int i : a) {
- System.out.print(i + " ");
- }
- }
- }
Ouput: 2 2 3 4 4 5 5 32 43 45 66
Average time complexity: O(n2)
Average time complexity: O(n2)
// Bubble sort algorithm in decreasing order:
- public class BubbleSortAlgorithm {
- public static void main(String[] args) {
- int a[] = { 3, 4, 5, 43, 2, 2, 45, 66, 5, 4, 32 };
- int temp;
- for (int i = 0; i < a.length; i++) {
- for (int j = 0; j < a.length-1; j++) {
- if (a[j] < a[j + 1]) {
- temp = a[j];
- a[j] = a[j + 1];
- a[j + 1] = temp;
- }
- }
- }
- for (int i : a) {
- System.out.print(i + " ");
- }
- }
- }
Output: 66 45 43 32 5 5 4 4 3 2 2
Average time complexity: O(n2)
Average time complexity: O(n2)
// II Method: Increasing order
- public class BubbleSort{
- public static void main(String[] args) {
- int arr[] = { 5, 6, 4, 3, 3, 5, 6, 9, 8 };
- for (int i = 0; i < arr.length; i++) {
- for (int j = 0; j < arr.length; j++) {
- if (arr[i] < arr[j]) {
- int temp = arr[i];
- arr[i] = arr[j];
- arr[j] = temp;
- }
- }
- }
- for (int i : arr)
- System.out.print(i + " ");
- }
- }
Output: 3 3 4 5 5 6 6 8 9
Average time complexity: O(n2)
Average time complexity: O(n2)
Bubble sort in decreasing order:
- public class BubbleSort {
- public static void main(String[] args) {
- int arr[] = { 5, 6, 4, 3, 3, 5, 6, 9, 8 };
- for (int i = 0; i < arr.length; i++) {
- for (int j = 0; j < arr.length; j++) {
- if (arr[i] > arr[j]) {
- int temp = arr[i];
- arr[i] = arr[j];
- arr[j] = temp;
- }
- }
- }
- for (int i : arr)
- System.out.print(i + " ");
- }
- }
Output: 9 8 6 6 5 5 4 3 3
Average time complexity: O(n2)
Average time complexity: O(n2)
No comments:
Post a Comment