0

I created some code that sorts an array using bubble sort but I was told that there is a variation of bubble sort that performs better, so I was wondering if there is an better version of bubble sort. For example, I'm using the regular version if it below:

package termproject3;

import java.util.Random;
import java.util.Scanner;
import java.util.concurrent.TimeUnit;


public class TermProject3 {

/**
 * @param args the command line arguments
 */
public static void main(String[] args) {
    // TODO code application logic here 
    Scanner sc = new Scanner(System.in);    
    System.out.println("please enter the size of the array:");
    int n = sc.nextInt();
     System.out.println("Enter the  number of iterations: ");
    int num_i = sc.nextInt();
    int swap;
    int array[] = new int[n];

    Random r = new Random();
    long startTime = System.nanoTime();
    for (int t = 0; t < num_i; t++){
     System.out.println();   
    System.out.println( t+1 + ".- Array to be sorted: ");

    for (int i = 0; i < n; i++) {
        array[i] = r.nextInt(array.length);

        System.out.print(array[i] + ", ");
    }

    System.out.println();

    for (int i = 0; i < (n - 1); i++) {
        for (int d = 0; d < n - i - 1; d++) {
            if (array[d] > array[d + 1]) {
                swap = array[d];
                array[d] = array[d + 1];
                array[d + 1] = swap;
            }
        }
    }

    System.out.println("Sorted list using bubble sort :");

    for (int i = 0; i < n; i++) {
        System.out.print(array[i] + ", ");
    }
    System.out.println();

}
 long running_time = System.nanoTime() - startTime;

System.out.println("elapsed time: " +running_time+ " nano seconds"); 

System.out.println("which is " + running_time/1E9 + " seconds");
}
}
UnPatoCuacCuac
  • 315
  • 2
  • 7
  • 18

2 Answers2

4

I don't know why you'd want to use bubble sort, but Collections.sort(List) and Collections.sort(List, Comparator) implement quicksort that you can use.

Mureinik
  • 297,002
  • 52
  • 306
  • 350
0

This answer may be helpful to you: Optimized Bubble Sort (Java)

It is notable to mention that optimizing a bubble sort is a silly exercise as much quicker, more elegant methods exist:

Collections.sort(List)
Community
  • 1
  • 1
TayTay
  • 6,882
  • 4
  • 44
  • 65