Thursday, April 19, 2018

Bubble Sort Algorithm

// Bubble sort algorithm in increasing order:
  1. public class BubbleSortAlgorithm {

  2. public static void main(String[] args) {
  3. int a[] = { 3, 4, 5, 43, 2, 2, 45, 66, 5, 4, 32 };
  4. int temp;

  5. for (int i = 0; i < a.length; i++) {
  6. for (int j = 0; j < a.length-1; j++) {
  7. if (a[j] > a[j + 1]) {
  8. temp = a[j];
  9. a[j] = a[j + 1];
  10. a[j + 1] = temp;
  11. }
  12. }
  13. }
  14. for (int i : a) {
  15. System.out.print(i + " ");
  16. }
  17. }
  18. }
Ouput: 2 2 3 4 4 5 5 32 43 45 66
Average time complexity: O(n2)

// Bubble sort algorithm in decreasing order:
  1. public class BubbleSortAlgorithm {

  2. public static void main(String[] args) {
  3. int a[] = { 3, 4, 5, 43, 2, 2, 45, 66, 5, 4, 32 };
  4. int temp;

  5. for (int i = 0; i < a.length; i++) {
  6. for (int j = 0; j < a.length-1; j++) {
  7. if (a[j] < a[j + 1]) {
  8. temp = a[j];
  9. a[j] = a[j + 1];
  10. a[j + 1] = temp;
  11. }
  12. }
  13. }
  14. for (int i : a) {
  15. System.out.print(i + " ");
  16. }
  17. }
  18. }
Output: 66 45 43 32 5 5 4 4 3 2 2 
Average time complexity: O(n2)

// II Method: Increasing order
  1. public class BubbleSort{

  2. public static void main(String[] args) {

  3. int arr[] = { 5, 6, 4, 3, 3, 5, 6, 9, 8 };
  4. for (int i = 0; i < arr.length; i++) {
  5. for (int j = 0; j < arr.length; j++) {
  6. if (arr[i] < arr[j]) {
  7. int temp = arr[i];
  8. arr[i] = arr[j];
  9. arr[j] = temp;
  10. }
  11. }
  12. }
  13. for (int i : arr)
  14. System.out.print(i + " ");
  15. }
  16. }
Output: 3 3 4 5 5 6 6 8 9
Average time complexity: O(n2)

Bubble sort in decreasing order:
  1. public class BubbleSort {

  2. public static void main(String[] args) {

  3. int arr[] = { 5, 6, 4, 3, 3, 5, 6, 9, 8 };
  4. for (int i = 0; i < arr.length; i++) {
  5. for (int j = 0; j < arr.length; j++) {
  6. if (arr[i] > arr[j]) {
  7. int temp = arr[i];
  8. arr[i] = arr[j];
  9. arr[j] = temp;
  10. }
  11. }
  12. }
  13. for (int i : arr)
  14. System.out.print(i + " ");
  15. }
  16. }
Output: 9 8 6 6 5 5 4 3 3
Average time complexity: O(n2)

No comments:

Post a Comment

Blueprint for self-improvement

To learn faster: Make the process fun To understand yourself : Write To understand the world better : Read To build deeper connection : Lis...