Home
Time Box
Calculator
Snake
Blogs
Hacks

Algorithmic • 3 min read

Description

bubble sort and my part in it


Explanation of bubble sort

Code behind it

import java.util.ArrayList;

public class Timing {
    ArrayList<Integer> array = new ArrayList<>();
    //Create a method that adds random number to an array, it takes a parameter for how many random terms to create
    public void addRandom(int n){
        for(int i = 0; i < n; i++){
            array.add((int)(Math.random()*100));
        }
    }

    //Bubble sort algorithm with a timer
    public void bubbleSort(){
        long startTime = System.currentTimeMillis();
        for(int i = 0; i < array.size(); i++){
            for(int j = 0; j < array.size()-1; j++){
                if(array.get(j) > array.get(j+1)){
                    int temp = array.get(j);
                    array.set(j, array.get(j+1));
                    array.set(j+1, temp);
                }
            }
        }
        long endTime = System.currentTimeMillis();
        System.out.println("Bubble sort took: " + (endTime - startTime) + " milliseconds");
    }

    public static void main(String[] args) {
        Timing t = new Timing();
        t.addRandom(1000);

        t.bubbleSort();

    }
}

Timing.main(null);

Bubble sort took: 38 milliseconds

My role

img