HiveBrain v1.2.0
Get Started
← Back to all entries
snippetjavaMinor

Using BubbleSort to sort numbers into ascending & descending order

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
orderdescendingintonumberssortusingbubblesortascending

Problem

I have created a simple implementation of the bubble sort algorithm. I have tried to make it as efficient as possible by following pseudocode which I have provided below, making some slight modifications to suit my needs.

The pseudocode:

procedure bubbleSort( A : list of sortable items )
n = length(A)
repeat
swapped = false
for i = 1 to n-1 inclusive do
if A[i-1] > A[i] then
swap(A[i-1], A[i])
swapped = true
end if
end for
n = n - 1
until not swapped
end procedure


My code:

`import java.util.Arrays;
import java.util.Scanner;
public class BubbleSortNumeric {
public static void main (String [] args) {
System.out.println("Enter a set of integers seperated by a space...");
Integer [] unsortedData = getDataInput();
Integer [] unsortedData2 = new Integer[unsortedData.length];
System.arraycopy(unsortedData, 0, unsortedData2, 0, unsortedData.length);
Integer [] sortedDataAscending;
Integer [] sortedDataDescending;
long start = System.nanoTime();
sortedDataAscending = bubbleSortAscending(unsortedData);
sortedDataDescending = bubbleSortDescending(unsortedData2);
long stop = System.nanoTime();
System.out.println("Ascending: " + Arrays.toString(sortedDataAscending));
System.out.println("Descening: " + Arrays.toString(sortedDataDescending));
System.out.println("Execution time: " + ((stop - start) / 1e+6) + "ms.");
}

private static Integer [] getDataInput() {
Integer [] userInput = {};
String strInput;
try(Scanner sc = new Scanner(System.in)) {
strInput = sc.nextLine();
}
String [] inputData = strInput.split("\\s+");
try {
userInput = Arrays.asList(inputData).stream().map(Integer::valueOf).toArray(Integer[]::new);
}catch(NumberFormatException e) {
System.out.println("ERROR. Invalid i

Solution

Points On Your Existing Code

  • unsortedData and unsortedData2 look weird to me. Try appending a 1 to unsortedData to make them line up.



  • Arrays has a utility method called copyOf(array, length) that internally uses System.arraycopy(). It will save you a few lines.



  • sortedAscendingData or ascendingSortedData makes more sense than sortedDataAscending. Same for sortedDataDescending. This is because [adjective(s)][noun] is more natural than [adjective(s)][noun][more adjectives]



  • swapped == true is redundant. The while (or if, and so on) construct needs a boolean only. Therefore, you can shorten your swapped == true to simply swapped and (for example) swapped == false to !swapped.



  • If you are using Scanner, then stick to it. Scanner is always preferred over String.split().



  • You should declare variables close to where you need them (or in the smallest scope possible). int temp = array[i]; will do you no harm.



  • Try to keep typos (i.e. typographical errors) like seperated and Descening to a minimum.



  • If you really want performance, why are you using Integer? You should be using int. There is a special mapToInt method to deal with ints. Carrying around an array of Integers is expensive in terms of memory and computational steps ( due boxing and unboxing).



  • If you really want to use Integer, generalise your code by using Number instead. You can directly call the compareTo() method which is implemented in all classes like Long, Double, BigInteger, etc. It helps reduce code redundancy, but it doesn't avoid the extra boxing/unboxing. This is an example of a readability/performance trade-off.



  • Comparator is a useful class that helps you compare the Comparable implementations in your way. Since you want performance I won't discuss it here any further. But it would be better if you take a look at it anyway.



  • One final point on final: This keyword is used to signify that the concerned variable is now effectively a constant, i.e. its value (including its contents) cannot change. Therefore, it makes no sense to add it before the arguments in the sorting methods, as you are changing them (internally).



The Refactored Code

Here is my version of the code, using ints and ensures better performance due to absence of overheads. See how I ditched split()? I haven't written this from scratch. I just took your code and fixed the parts that needed fixing. I left the others intact.

```
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
import java.util.Scanner;

public class BubbleSortNumeric {
public static void main(String[] args) {
System.out.println("Enter a set of integers separated by white space.");
int[] unsortedData1 = getInts();
int[] unsortedData2 = Arrays.copyOf(unsortedData1, unsortedData1.length);
long start = System.nanoTime();
int[] sortedAscendingData = bubbleSortAscending(unsortedData1);
int[] sortedDescendingData = bubbleSortDescending(unsortedData2);
long stop = System.nanoTime();
System.out.println("Ascending: " + Arrays.toString(sortedAscendingData));
System.out.println("Descending: " + Arrays.toString(sortedDescendingData));
System.out.println("Execution time: " + ((stop - start) / 1e+6) + "ms.");
}

private static int[] getInts() {
int[] userInput = {};
List strings = new ArrayList<>();
try (Scanner sc = new Scanner(System.in)) {
while (sc.hasNext()) {
strings.add(sc.next());
}
}
try {
userInput = strings
.stream()
.mapToInt(Integer::parseInt)
.toArray();
} catch (NumberFormatException e) {
System.out.println("ERROR. Invalid input.\n" + e.getMessage());
}
return userInput;
}

private static int[] bubbleSortAscending(int[] array) {
int n = array.length;
if (n == 1) {
return array;
}
boolean swapped;
do {
swapped = false;
for (int i = 1; i array[i]) {
int temp = array[i - 1];
array[i - 1] = array[i];
array[i] = temp;
swapped = true;
}
}
n--;
} while (swapped);
return array;
}

private static int[] bubbleSortDescending(int[] array) {
int n = array.length;
if (n == 1) {
return array;
}
boolean swapped;
do {
swapped = false;
for (int i = 1; i < n; i++) {
if (array[i - 1] < array[i]) {
int temp = array[i];
array[i] = array[i - 1];
array[i - 1] = temp;
swapped = true;
}

Code Snippets

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
import java.util.Scanner;

public class BubbleSortNumeric {
    public static void main(String[] args) {
        System.out.println("Enter a set of integers separated by white space.");
        int[] unsortedData1 = getInts();
        int[] unsortedData2 = Arrays.copyOf(unsortedData1, unsortedData1.length);
        long start = System.nanoTime();
        int[] sortedAscendingData = bubbleSortAscending(unsortedData1);
        int[] sortedDescendingData = bubbleSortDescending(unsortedData2);
        long stop = System.nanoTime();
        System.out.println("Ascending: " + Arrays.toString(sortedAscendingData));
        System.out.println("Descending: " + Arrays.toString(sortedDescendingData));
        System.out.println("Execution time: " + ((stop - start) / 1e+6) + "ms.");
    }

    private static int[] getInts() {
        int[] userInput = {};
        List<String> strings = new ArrayList<>();
        try (Scanner sc = new Scanner(System.in)) {
            while (sc.hasNext()) {
                strings.add(sc.next());
            }
        }
        try {
            userInput = strings
                    .stream()
                    .mapToInt(Integer::parseInt)
                    .toArray();
        } catch (NumberFormatException e) {
            System.out.println("ERROR. Invalid input.\n" + e.getMessage());
        }
        return userInput;
    }

    private static int[] bubbleSortAscending(int[] array) {
        int n = array.length;
        if (n == 1) {
            return array;
        }
        boolean swapped;
        do {
            swapped = false;
            for (int i = 1; i < n; i++) {
                if (array[i - 1] > array[i]) {
                    int temp = array[i - 1];
                    array[i - 1] = array[i];
                    array[i] = temp;
                    swapped = true;
                }
            }
            n--;
        } while (swapped);
        return array;
    }

    private static int[] bubbleSortDescending(int[] array) {
        int n = array.length;
        if (n == 1) {
            return array;
        }
        boolean swapped;
        do {
            swapped = false;
            for (int i = 1; i < n; i++) {
                if (array[i - 1] < array[i]) {
                    int temp = array[i];
                    array[i] = array[i - 1];
                    array[i - 1] = temp;
                    swapped = true;
                }
            }
            n--;
        } while (swapped);
        return array;
    }
}

Context

StackExchange Code Review Q#104530, answer score: 5

Revisions (0)

No revisions yet.