Doesn't Matter
Doesn't Matter

Reputation: 405

BubbleSort Implementation

I tried to make an implementation of bubble sort, but I am not sure whether it is correct or not. If you can give it a look and if it is a bubble sort and can be done in better way please don't be shy. Here is the code:

package Exercises;

import java.util.*;

public class BubbleSort_6_18 
{
    public static void main(String[] args) 
    {
        Random generator = new Random();

        int[] list = new int[11];
        for(int i=0; i<list.length; i++)
        {
            list[i] = generator.nextInt(10);
        }

        System.out.println("Original Random array: ");
        printArray(list);

        bubbleSort(list);

        System.out.println("\nAfter bubble sort: ");
        printArray(list);
    }

    public static void bubbleSort(int[] list)
    {
        for(int i=0; i<list.length; i++)
        {
            for(int j=i + 1; j<list.length; j++)
            {
                if(list[i] > list[j])
                {
                    int temp = list[i];
                    list[i] = list[j];
                    list[j] = temp;
                }
            }

        }
    }

    public static void printArray(int[] list)
    {
        for(int i=0; i<list.length; i++)
        {
            System.out.print(list[i] + ", ");
        }
    }
}

Upvotes: 0

Views: 31088

Answers (17)

YektaDev
YektaDev

Reputation: 540

Here's an implementation for the bubble sort algorithm using Stack:

static void bubbleSort(int[] elements) {
    Stack<Integer> primaryStack = new Stack<>();
    Stack<Integer> secondaryStack = new Stack<>();
    int lastIndex = elements.length - 1;

    for (int element : elements) {
        primaryStack.push(element);
    } // Now all the input elements are in primaryStack

    // Do the bubble sorting
    for (int i = 0; i < elements.length; i++) {
        if (i % 2 == 0) sort(elements, i, primaryStack, secondaryStack, lastIndex);
        else sort(elements, i, secondaryStack, primaryStack, lastIndex);
    }
}

private static void sort(int[] elements, int i, Stack<Integer> stackA, Stack<Integer> stackB, int lastIndex) {
    while (!stackA.isEmpty()) { // Move an element from stack A to stack B
        int element = stackA.pop();

        if (stackB.isEmpty() || element >= stackB.peek()) { // Don't swap, just push
            stackB.push(element);
        } else { // Swap, then push
            int temp = stackB.pop();
            stackB.push(element);
            stackB.push(temp);
        }
    }
    elements[lastIndex - i] = stackB.pop();
}

Upvotes: 0

Keshav Gera
Keshav Gera

Reputation: 11244

function bubbleSort(arr,n) {
    if (n == 1)  // Base case
    return; 
    // One pass of bubble sort. After
    // this pass, the largest element
    // is moved (or bubbled) to end. and count++

    for (let i = 0; i <n-1; i++){
        if (arr[i] > arr[i + 1]) 
        { 
            let temp = arr[i]; 
            arr[i] = arr[i + 1]; 
            arr[i + 1] = temp; 
        }
    }
    // Largest element is fixed,
    // recur for remaining array
    console.log("Bubble sort Steps ", arr, "   Bubble sort array length reduce every recusrion ", n);
    bubbleSort(arr, n - 1);
}
let arr1 = [64, 3400, 251, 12, 220, 11, 125]
bubbleSort(arr1, arr1.length); 
console.log("Sorted array : ", arr1);

enter image description here

enter image description here

Upvotes: 0

duyuanchao
duyuanchao

Reputation: 4303

package com.examplehub.sorts;

public class BubbleSort implements Sort {

  /**
   * BubbleSort algorithm implements.
   *
   * @param numbers the numbers to be sorted.
   */
  public void sort(int[] numbers) {
    for (int i = 0; i < numbers.length - 1; ++i) {
      boolean swapped = false;
      for (int j = 0; j < numbers.length - 1 - i; ++j) {
        if (numbers[j] > numbers[j + 1]) {
          int temp = numbers[j];
          numbers[j] = numbers[j + 1];
          numbers[j + 1] = temp;
          swapped = true;
        }
      }
      if (!swapped) {
        break;
      }
    }
  }

  /**
   * Generic BubbleSort algorithm implements.
   *
   * @param array the array to be sorted.
   * @param <T> the class of the objects in the array.
   */
  public <T extends Comparable<T>> void sort(T[] array) {
    for (int i = 0; i < array.length - 1; ++i) {
      boolean swapped = false;
      for (int j = 0; j < array.length - 1 - i; ++j) {
        if (array[j].compareTo(array[j + 1]) > 0) {
          T temp = array[j];
          array[j] = array[j + 1];
          array[j + 1] = temp;
          swapped = true;
        }
      }
      if (!swapped) {
        break;
      }
    }
  }
}

source from

Upvotes: 0

Ryan Fung
Ryan Fung

Reputation: 2217

I think you got the idea of bubble sort by looking at your code:

Bubble sort usually works like the following: Assume aNumber is some random number:

for (int i = 0; i < aNumber; i++)
{
     for(int j = 0; j < aNumber; j++)

      //Doing something with i and j, usually running it as a loop for 2D array
      //array[i][j] will give you a complete sort.
}

How bubble sort works is it iterates through every single possible spot of the array. i x j times The down side to this is, it will take square the number of times to sort something. Not very efficient, but it does get the work done in the easiest way.

Upvotes: 1

Thilina De Silva
Thilina De Silva

Reputation: 391

    int[] nums = new int[] { 6, 3, 2, 1, 7, 10, 9 };

        for(int i = nums.Length-1; i>=0; i--)
            for(int j = 0; j<i; j++)
            {
                int temp = 0;
                if( nums[j] < nums[j + 1])
                {
                    temp = nums[j];
                    nums[j] = nums[j + 1];
                    nums[j + 1] = temp;
                }
            }

Upvotes: 0

Py-Coder
Py-Coder

Reputation: 2234

Yes it seems to be Bubble sort swapping the elements

Bubble sort

void bubbleSort(int arr[])
{
    int n = arr.length;
    for (int i = 0; i < n-1; i++)
        for (int j = 0; j < n-i-1; j++)
            if (arr[j] > arr[j+1])
            {
                // swap temp and arr[i]
                int temp = arr[j];
                arr[j] = arr[j+1];
                arr[j+1] = temp;
            }
}

It will give in worst case O(n^2) and even if array is sorted.

Upvotes: 1

Piotr Jankowski
Piotr Jankowski

Reputation: 146

Mohammod Hossain implementation is quite good but he does alot of unecessary iterations, sadly he didnt accept my edit and i can't comment due to reputations points so here is how it should look like:

public void sort(int[] array) {
        int temp = 0;
        boolean swap = true;
        int range = array.length - 1;
        while (swap) {
            swap = false;
            for (int i = 0; i < range; i++) {
                if (array[i] > array[i + 1]) {
                    temp = array[i];
                    array[i] = array[i + 1];
                    array[i + 1] = temp;
                    swap = true;
                }
            }
            range--;
        }
    }

Upvotes: 6

Ahmad Abdelghany
Ahmad Abdelghany

Reputation: 13218

Short Answer: This is definitely NOT Bubble sort. It is a variant of Selection sort (a less efficient variant than the commonly known one).

It might be helpful to see a visualization of how they work on VisuAlgo

Why this is not bubble sort?

Because you loop over the array and compare each element to each other element on its right. if the right element is smaller you swap. Thus, at the end of the first outer loop iteration you will have the smallest element on the left most position and you have done N swaps in the worst case (think of a reverse-ordered array).

If you think about it, you did not really need to do all these swaps, you could have searched for the minimum value on the right then after you find it you swap. This is simply the idea of Selection sort, you select the min of remaining unsorted elements and put it in its correct position.

How does bubble sort look like then?

In bubble sort you always compare two adjacent elements and bubble the larger one to the right. At the end of the first iteration of the outer loop, you would have the largest element on the right-most position. The swap flag stops the outer loop when the array is already sorted.

void bubbleSort(int[] arr) {
    boolean swap = true;       
    for(int i = arr.length - 1; i > 0 && swap; i--) {
        swap = false;
        // for the unsorted part of the array, bubble the largest element to the right.
        for (int j = 0; j < i; j++) {
            if (arr[j] > arr[j+1]) {
                // swap
                int temp = arr[j];
                arr[j] = arr[j+1];
                arr[j+1] = temp;
                swap = true;
            }
        }
    }
}

Upvotes: 2

asthiwanka
asthiwanka

Reputation: 447

class BubbleSort {

public static void main(String[] args) {

    int a[] = {5,4,3,2,1};
    int length = a.length - 1;

    for (int i = 0 ; i < length ; i++) {
        for (int j = 0 ; j < length-i ; j++) {
            if (a[j] > a[j+1]) {
                int swap = a[j];
                a[j] = a[j+1];
                a[j+1] = swap;
            }
        }
    }

    for (int x : a) {
        System.out.println(x);
    }
}

}

Upvotes: 0

Mohammod Hossain
Mohammod Hossain

Reputation: 4114

private static int [] bublesort (int[] list , int length) {

    boolean swap = true;
    int temp;

    while(swap){

        swap = false;

        for(int i = 0;i < list.length-1; i++){              
            if(list[i] > list[i+1]){
                temp = list[i];
                list[i] = list[i+1];
                list[i+1] = temp;                   
                swap = true;
            }
        }
    }
    return list;
}

Upvotes: 9

Mohit Motiani
Mohit Motiani

Reputation: 29

/*
Implementation of Bubble sort using Java
*/

import java.util.Arrays;
import java.util.Scanner;


public class BubbleSort {

    /**
     * @param args
     */
    public static void main(String[] args) {
        // TODO Auto-generated method stub
            Scanner in = new Scanner(System.in);
            System.out.println("Enter the number of elements of array");
            int n = in.nextInt();
            int []a = new int[n];
            System.out.println("Enter the integer array");
            for(int i=0; i<a.length; i++)
            {
                a[i]=in.nextInt();
            }
            System.out.println("UnSorted array: "+ Arrays.toString(a));         
            for(int i=0; i<n; i++)
            {
                for(int j=1; j<n; j++)
                {
                    if(a[j-1]>a[j])
                    {
                        int temp = a[j-1];
                        a[j-1]=a[j];
                        a[j]=temp;
                    }
                }
            }
            System.out.println("Sorted array: "+ Arrays.toString(a));           
    }
}


/*
****************************************
Time Complexity: O(n*n)
Space Complexity: O(1)
****************************************
*/

Upvotes: 0

Thanumoorthy
Thanumoorthy

Reputation: 13

Above code is looks like implementation Selection sort , it's not a bubble sort.

Please find below code for bubble sort.

Class BubbleSort {
public static void main(String []args) {
int n, c, d, swap;
Scanner in = new Scanner(System.in); 
System.out.println("Input number of integers to sort");
n = in.nextInt();

int array[] = new int[n]; 
System.out.println("Enter " + n + " integers");

for (c = 0; c < n; c++) 
  array[c] = in.nextInt();

for (c = 0; c < ( n - 1 ); c++) {
  for (d = 0; d < n - c - 1; d++) {
    if (array[d] > array[d+1]) /* For descending order use < */
    {
      swap       = array[d];
      array[d]   = array[d+1];
      array[d+1] = swap;
    }
  }
}

System.out.println("Sorted list of numbers");

for (c = 0; c < n; c++) 
  System.out.println(array[c]);
}
}

Upvotes: 0

zoha khan
zoha khan

Reputation: 21

public class BubbleSort {
    public static void main(String[] args) {
        int arr[] = {64, 34, 25, 12, 22, 11, 90};
        BubbleSort client=new BubbleSort();
        int[] result=client.bubbleSort(arr);
        for(int i:result)
        {
            System.out.println(i);
        }
    }
    public int[] bubbleSort(int[] arr)
    {
        int n=arr.length;
        for(int i=0;i<n;i++)
        {
            for(int j=0;j<n-i-1;j++) 
                if(arr[j]>arr[j+1])
             swap(arr,j,j+1);   
        }
        return arr;
    }
    private int[] swap(int[] arr, int i, int j) {
        int temp=arr[i];
        arr[i]=arr[j];
        arr[j]=temp;
        return arr;
    }


}

Upvotes: 0

Matthias
Matthias

Reputation: 4677

A bubblesort version with while loops from my first undergraduate year ("the BlueJ era").

public static void bubbleSort()
    {
        int[] r = randomArrayDisplayer();
        int i = r.length;
        while(i!=0){
            int j = 0;
            while(j!=i-1){
                if(r[j+1]<r[j]){
                    swap(r,j,j+1);
                }
                j++;
            }
            i--;
        }
    }

private static void swap(int[] r, int u, int v)
    {
       int value = r[u];
       r[u] = r[v];
       r[v] = value;
       arrayDisplayer(r);
    }

My advice is to display every step in order to be sure of the correct behaviour.

Upvotes: 0

Bhaskar R
Bhaskar R

Reputation: 21

{
    System.out.println("The Elments Before Sorting:");
    for(i=0;i<a.length;i++)
    {
        System.out.print(a[i]+"\t");
    }
    for(i=1;i<=a.length-1;i++)
    {
      for(j=0;j<=a.length-i-1;j++)
      {
          if((a[j])>(a[j+1]))
          {
              temp=a[j];
              a[j]=a[j+1];
              a[j+1]=temp;
            }
       }
      System.out.println("The Elements After Sorting:");
      for(i=0;i<a.length;i++)
      {
            System.out.println(a[i]+"\t");
      }
    }
}

Upvotes: 2

Viktor Mellgren
Viktor Mellgren

Reputation: 4506

  • You can loop over the array until no more elements are swapped
  • When you put the element at the last position you know it's the largest, so you can recuce the inner loop by 1

Upvotes: 0

Ivaylo Strandjev
Ivaylo Strandjev

Reputation: 70929

This is the calssical implementation for bubble sort and it seems to be OK. There are several optimizations that can be done, but the overall idea is the same. Here are some ideas:

  • If there is an iteration of the outer cycle when no swap is performed in the inner cycle, then break, no use to continue
  • On each iteration of the outer cycle swap the direction of the inner one - do it once left to right and then do it once right to left(this helps avoid elements moving slowly towards the right end).

Upvotes: 2

Related Questions