snippetjavaMinor
Using BubbleSort to sort numbers into ascending & descending order
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:
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
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
The Refactored Code
Here is my version of the code, using
```
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;
}
unsortedDataandunsortedData2look weird to me. Try appending a1tounsortedDatato make them line up.
Arrayshas a utility method calledcopyOf(array, length)that internally usesSystem.arraycopy(). It will save you a few lines.
sortedAscendingDataorascendingSortedDatamakes more sense thansortedDataAscending. Same forsortedDataDescending. This is because[adjective(s)][noun]is more natural than[adjective(s)][noun][more adjectives]
swapped == trueis redundant. Thewhile(orif, and so on) construct needs a boolean only. Therefore, you can shorten yourswapped == trueto simplyswappedand (for example)swapped == falseto!swapped.
- If you are using
Scanner, then stick to it.Scanneris always preferred overString.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
seperatedandDesceningto a minimum.
- If you really want performance, why are you using
Integer? You should be usingint. There is a specialmapToIntmethod to deal withints. Carrying around an array ofIntegers is expensive in terms of memory and computational steps ( due boxing and unboxing).
- If you really want to use
Integer, generalise your code by usingNumberinstead. You can directly call thecompareTo()method which is implemented in all classes likeLong,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.
Comparatoris a useful class that helps you compare theComparableimplementations 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.