Advertisement
gelita

Bubble Sort

Feb 17th, 2020
195
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 5 1.38 KB | None | 0 0
  1. // package whatever; // don't place package name!
  2.  
  3. import java.io.*;
  4. /**
  5.  *  Quadratic Sorts
  6.  *
  7.  *
  8.  *  Problem 3: Bubble Sort
  9.  *
  10.  *  Prompt:    Given an unsorted array of integers, return the array
  11.  *             sorted using bubble sort.
  12.  *
  13.  *  Input:     input {Array}
  14.  *  Output:    {Array}
  15.  *
  16.  *  Example:   [3,9,1,4,7] --> [1,3,4,7,9]
  17.  */
  18.  
  19. import java.util.*;
  20.  
  21. class BasicSort {
  22.  
  23.     public static void main (String[] args) {
  24.     int[] arr = {0};
  25.         System.out.println("output" + Arrays.toString(bubble(arr)));
  26.     }
  27.     public static int[] bubble(int[] input) {
  28.       int index = 0;
  29.       int j = 0;
  30.       int temp = 0;
  31.       int len = input.length;
  32.       boolean swappedFlag;
  33.       for(index = 0; index < len -1; index++){
  34.         swappedFlag = false;
  35.         System.out.println("index: " + index);
  36.         // j resets to first element after every pass
  37.         for(j = 0; j < len -1 -index; j++){
  38.           System.out.println("j : " + j);
  39.           if(input[j] > input[j+1]){
  40.             temp = input[j];
  41.             input[j] = input[j+1];
  42.             input[j+1] = temp;
  43.             swappedFlag = true;
  44.           }
  45.         }
  46.         //if  now swap made, break from the loop
  47.         if(swappedFlag == false){
  48.           //no swaps made in the last pass
  49.           //therefore elements are sorted, break
  50.           break;
  51.         }
  52.       }
  53.     return input;
  54.     }
  55. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement