I've written a code to input the name, day and time of a few shows, with the option to have it sorted (bubble sort) by day and name. I'm using 1.4.2 (because I have to) and an ArrayList along with a simple class.
I've been staring at this for hours, left and came back to it a bunch of times, but unfortunately, it isn't working! Any idea why?! Here's my code:
//method to sort and display info
public static void sortDay(){
for(int i = 0; i < show.size() - 1; i++) {
for(int j = 0; j < show.size() - 1; j++){
showInfo current = (showInfo)show.get(j);
showInfo next = (showInfo)show.get(j+1);
if (current.day.compareTo(next.day) < 0) {
showInfo temp = new showInfo();
temp.name = ((showInfo)show.get(j)).name;
temp.day = ((showInfo)show.get(j)).day;
temp.time = ((showInfo)show.get(j)).time;
((showInfo)show.get(j)).time = ((showInfo)show.get(i)).time;
((showInfo)show.get(j)).day = ((showInfo)show.get(i)).day;
((showInfo)show.get(j)).name = ((showInfo)show.get(i)).name;
((showInfo)show.get(i)).time = temp.time;
((showInfo)show.get(i)).day = temp.day;
((showInfo)show.get(i)).name = temp.name;
}
}
}
System.out.println("Show Information");
for (int i = 0; i < show.size(); i++){
System.out.println("Name: " + ((showInfo)show.get(i)).name);
System.out.println("Day: " + ((showInfo)show.get(i)).day);
System.out.println("Time: " + ((showInfo)show.get(i)).time);
}
}
Any help would be great! Thanks in advance!
First, I'll assume you're using some kind of List - likely an ArrayList.
That said, the main operations for Bubble Sort are described as follows:
Compare for ordering
Create temporary variable
Place left value into temporary variable
Place right value into left value
Place old left value into right value from temporary value
You're shuffling about the fields, which will lead to confusion and bugs. Use the above approach instead.
Here it is illustrated with generics (so you don't have to cast anymore), and a capital class name, as is the convention. I don't have a temporary variable in this example, as I already have a reference to current.
List<ShowInfo> show = new ArrayList<>(); // assume populated
public static void sortDay(){
for(int i = 0; i < show.size(); i++) {
for(int j = 0; j < show.size() && j != i; j++) {
ShowInfo current = show.get(i);
ShowInfo next = show.get(j);
// If the current day is greater than the next day, we need to swap.
// Adjust to suit your business logic (if current is less than next).
if (current.day.compareTo(next.day) > 0) {
show.set(i, next);
show.set(j, current);
}
}
}
}
For a generic way of doing this, perhaps you could try something like:
public static <T extends Comparable> void sort(final List<T> list){
boolean remaining;
do{
remaining = false;
for(int i = 0; i < list.size()-1; i++){
final T current = list.get(i);
final T next = list.get(i+1);
if(current.compareTo(next) < 0){
list.set(i, next);
list.set(i+1, current);
remaining = true;
}
}
}while(remaining);
}
How do you fix it?
I'm just answering your question: how to fix the code you posted. For "how to improve it?" all other answers are way better than whatever I can come up with.
There are two points:
swap on the same index, in the inner for (index j)
correct swapping: where you have j write j+1 and where you have i write j
the other for is just so it will iterate enough times to get it sorted in the worst case (suggestions in other answers go for a while, much better)
That being said, the swapping pseudocode is:
if (show[j] < show[j+1]) {
temp = j+1
j+1 = j
j = temp
}
And here is the swapping code with the fixes:
if (current.day.compareTo(next.day) < 0) {
showInfo temp = new showInfo();
temp.name = ((showInfo)show.get(j+1)).name;
temp.day = ((showInfo)show.get(j+1)).day;
temp.time = ((showInfo)show.get(j+1)).time;
((showInfo)show.get(j+1)).time = ((showInfo)show.get(j)).time;
((showInfo)show.get(j+1)).day = ((showInfo)show.get(j)).day;
((showInfo)show.get(j+1)).name = ((showInfo)show.get(j)).name;
((showInfo)show.get(j)).time = temp.time;
((showInfo)show.get(j)).day = temp.day;
((showInfo)show.get(j)).name = temp.name;
}
And here is the printed result (assuming day - time - name for each show, so we are sorting on the first int):
Show Information before sort
610 - -72 - 1402
838 - -184 - 1096
-478 - 248 - 934
709 - 832 - -590
2007 - 954 - -315
Show Information after sort
2007 - 954 - -315
838 - -184 - 1096
709 - 832 - -590
610 - -72 - 1402
-478 - 248 - 934
public class myBubbleSort
{
private static int[] a;
public static void main(String[] args)
{
getArray(10);
System.out.println("Array before sorting");
printArray();
ascendingBubble();
System.out.println("Array after ascending sort");
printArray();
descendingBubble();
System.out.println("Array after descending sort");
printArray();
System.out.println();
System.out.println("Random sort");
getArray(10);
bubbleSort(true);
System.out.println("Array after Random sort");
printArray();
}
// print the number in random array
public static void printArray()
{
for (int i : a)
{
System.out.print(i + " ");
}
System.out.println();
}
// generate a random array to be sorted in ascending and descending order
public static void getArray(int size)
{
a = new int[size];
int item = 0;
for (int i = 0; i < size; i++)
{
item = (int) (Math.random() * 100);
a[i] = item;
}
}
// sort getArray in ascending order and bubblesort it
public static void ascendingBubble()
{
int temp;
System.out.println();
System.out.println("Ascending sort");
for (int i = 0; i < a.length - 1; i++)
{
for (int j = 0; j < a.length - 1; j++)
{
if (a[j] > a[j + 1])
{
temp = a[j];
a[j] = a[j + 1];
a[j + 1] = temp;
}
}
}
bubbleSort(true);
}
// sort getArray in descending order and bubblesort it
public static void descendingBubble()
{
int temp;
System.out.println();
System.out.println("Descending sort");
for (int i = 0; i < a.length - 1; i++)
{
for (int j = 0; j < a.length - 1; j++)
{
if (a[j] < a[j + 1])
{
temp = a[j];
a[j] = a[j + 1];
a[j + 1] = temp;
}
}
}
bubbleSort(true);
}
// bubble sort algorithm
public static void bubbleSort(boolean printTime)
{
boolean sorted = false;
int pass = 1;
int temp;
long startTime;
long endTime;
long duration;
startTime = System.nanoTime();
while (pass < a.length - 1 && (!sorted))
{
sorted = true;
for (int i = 0; i < a.length - 1; i++)
{
if (a[i] > a[i + 1])
{
temp = a[i];
a[i] = a[i + 1];
a[i + 1] = temp;
sorted = false;
}
}
pass = pass + 1;
}
endTime = System.nanoTime();
duration = (endTime - startTime);
if(printTime)
{
System.out.println(duration + " "+ " nano seconds");
}
}
}
Related
Regardless of the programming language you use. You will undoubtedly encounter data while dealing with arrays, particularly duplicates, that you will want to get rid of.
This is my Output
I already inputted the correct syntax of even list array is there something that I missed?
Anyone knows how to remove duplicate element in my even list?
Here's my code:
import java.util.*;
import java.util.Iterator;
public class ArrayBubbleSortwithOddandEven {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int size, temp;
System.out.print("Size of the list: ");
size = scanner.nextInt();
int number[] = new int[size];
int oddarray[] = new int[size];
int evenarray[] = new int[size];
int odd = 0;
int even = evenarray.length - 1;
for (int i = 0; i < number.length; i++) {
System.out.print("Input: ");
number[i] = scanner.nextInt();
}
for (int i = 0; i < size; i++) {
for (int swap = 1; swap < (size - i); swap++) {
if (number[swap - 1] > number[swap]) {
temp = number[swap - 1];
number[swap - 1] = number[swap];
number[swap] = temp;
}
}
}
for (int i = 0; i < number.length; i++) {
if (number[i] % 2 != 0) {
oddarray[odd++] = number[i];
} else {
evenarray[even--] = number[i];
}
}
for (int i = 0; i < number.length; i++) {
evenarray[even] = evenarray[i];
}
for (int i = 0; i < number.length; i++) {
oddarray[odd] = oddarray[i];
}
for (int i = 0; i < size; i++) { //Bubble sort
for (int swap = 1; swap < (size - i); swap++) {
if (evenarray[swap - 1] > evenarray[swap]) {
temp = evenarray[swap - 1];
evenarray[swap - 1] = evenarray[swap];
evenarray[swap] = temp;
}
}
}
System.out.println("Odd List:"); //Print Odd list
for (odd = 0; odd < oddarray.length; odd++) {
System.out.println("List " + odd + ": " + (oddarray[odd]));
}
System.out.println("Even List:"); //Print Even list
for (even = 0; even < evenarray.length; even++) {
System.out.println("List " + even + ": " + (evenarray[even]));
}
}
}
you can use a Set\HashMap to remember which number you already discover during your iteration. GOOD LUCK !
You can read about Data Structures - just google it :).
here a few questions that might help you understand.
Data Structures for hashMap, List and Set
Why key in HashMap can't be duplicated
how to find duplicate item position from set in java
I need help counting the swaps and comparisons i na selected bubble sort algorithm. I have tried passing in values to change them for each iteration but I cannot figure out how I can successfully implement a counter for the swaps and comparisons.
static void bubbleSort(int[] userArray_Copy, int n, int swaps) {
swaps = 0;
int temp;
for (int i = 0; i < n; i++) {
for (int j = 0 ; j < n-1 ; j++) {
if (userArray_Copy[j] > userArray_Copy[j + 1]){
temp = userArray_Copy[j];
userArray_Copy[j] = userArray_Copy[j+1];
userArray_Copy[j+1] = temp;
swaps++;
}
}
}
}
This question already has answers here:
What's the simplest way to print a Java array?
(37 answers)
Closed 7 years ago.
I have been working on this code for about a week; I am trying to make a program that generate random numbers and then sort them using the Bubble method, but I get this message "Bubble Sort: [I#ad3ba4". Does anyone see what is wrong I feel like this is so simple but I just can't find the problem.
import java.util.Random;
public class sortLibrary {
private static void bubbleSort(int[] list) {
int n = list.length;
int temp = 0;
for (int i = 0; i < n; i++) {
for (int j = 1; j < (n - 1); j++) {
if (list[j - 1] > list[j - 1]) {
temp = list[j - 1];
list[j - 1] = list[j];
list[j] = temp;
}
}
}
System.out.println("\nBubble Sort: " + list);
}
public static void main(String args[]) {
System.out.println("Unsorted list:");
Random numbers = new Random();
int list[] = new int[20];
for (int i = 0; i < 20; i++) {
list[i] = numbers.nextInt(100);
}
for (int i = 0; i < 20; i++) {
System.out.print(list[i] + " ");
}
bubbleSort(list);
}
}
You cannot simply print a list with a println(). That is only for strings.
Instead, replace list in your println() with Arrays.toString(list) to convert the array to a string for printing.
Or, you can print it out as an array, similar to #KyleGowen's answer. Here's an alternate form of a way to iterate over an array in Java easier:
String arrayToString = "";
for(int item : list) {
arrayToString += item + ", ";
}
System.out.println("Bubble sort: [" + arrayToString.substring(0, arrayToString.length()-2) + "]");
This should also print it nicely.
See both of these at TutorialPoint's online Java compiler.
Now, you can not print Array in java just like that. If you want to print all array you need to use index or use something like this:
System.out.println("\nBubble Sort: " + Arrays.toString(list));
Also in your if statement you have list[j - 1] > list[j-1]. I think there will be list[j - 1] > list[j]. So your code looks like:
import java.util.Arrays;
import java.util.Random;
public class bubble {
private static void bubbleSort(int[] list) {
int n = list.length;
int temp = 0;
for (int i = 0; i < n; i++) {
for (int j = 1; j < (n - 1); j++) {
if (list[j - 1] > list[j]) {
temp = list[j - 1];
list[j - 1] = list[j];
list[j] = temp;
}
}
}
System.out.println("\nBubble Sort: " + Arrays.toString(list));
}
public static void main(String args[]) {
System.out.println("Unsorted list:");
Random numbers = new Random();
int list[] = new int[20];
for (int i = 0; i < 20; i++) {
list[i] = numbers.nextInt(100);
}
for (int i = 0; i < 20; i++) {
System.out.print(list[i] + " ");
}
bubbleSort(list);
}
}
You are actually printing out the memory address of your list with
System.out.println("\nBubble Sort: "+list);
You will most likely want to loop through the list and print out the values. Something like:
System.out.print("\nBubble Sort: ");
for(int i = 0; i < list.length; i++){
System.out.print(list[i] + " ");
}
I hope this helps.
I was implementing a comparator, and it wasn't working, so I thought I'd write a basic bubble sort.
int[] numbers = { 5, 8, 14, 1, 5678 };
int tempVar;
for (int i = 0; i < numbers.length; i++)
{
for(int j = 0; j < numbers.length; j++)
{
if(numbers[i] > numbers[j + 1])
{
tempVar = numbers [j + 1];
numbers [j + 1]= numbers [i];
numbers [i] = tempVar;
}
}
}
for (int i = 0; i < numbers.length; i++)
{
System.out.println(numbers[i].toString());
}
Is this tutorial correct at all?
https://blog.udemy.com/bubble-sort-java/
I followed the example and applied it to Last Names in an arraylist, but the results are a bit wack.
String a;
String b;
Person c;
Person d;
for (int i=0; i< list.size(); i++){
for(int j=0; j< list.size()-1; j++){
a = list.get(i).getLastName();
b = list.get(j+1).getLastName();
c = list.get(i);
d = list.get(j+1);
if ( a.compareTo(b) < 0 ) {
Person temp = d;
list.set(j+1, c);
list.set(i, temp);
}
}
}
I'd really like to get a grip on a few methods (like figuring out why my comparator didn't work), but right now I'd just like to get a Bubble Sort to work correctly. Thanks.
In Bubble sort you need to compare only the adjacent elements and swap them(depending up on the condition).
If you are doing ascending order than comparing the adjacent elements and swap if(arr[j]>arr[j+1]).
This moves the largest elements to the end in the first iteration.Thus there are n-1 iterations in outer loop to sort the array where n is the length of the array.
Read this first Bubble sort as the tutorial you mentioned is completely wrong
Corrected code
for (int i = 0; i < numbers.length-1; i++)
{
for(int j = 0; j < numbers.length-i-1; j++)
{
if(numbers[j] > numbers[j + 1])
{
tempVar = numbers [j + 1];
numbers [j + 1]= numbers [j];
numbers [j] = tempVar;
}
}
}
Here is the working link
This is a strange and inefficient implementation, you compare each number which each other. Something like this is much more intuitive (could be improved a little performance-wise, but that is not the point, you will just save a lot of time not accidently making mistakes with the indices and if you really care about performance and not readability use mergesort or quicksort as Java does [Java is using quicksort for primitive types and mergesort for Objects, probably because for primitive types it doesn't matter if the algorithm is stable or not]):
public void bubbleSort(int[] arr) {
boolean change;
do {
change = false;
for (int i = 0; i < arr.length - 1; i++) {
if (arr[i] > arr[i + 1]) {
int temp = arr[i];
arr[i] = arr[i + 1];
arr[i + 1] = temp;
change = true;
}
}
} while (change);
}
Applied to your code (sorts ascending):
boolean change;
do {
change = false;
for (int i = 0; i < list.size() - 1; i++) {
c = list.get(i);
d = list.get(i + 1);
a = c.getLastName();
b = d.getLastName();
// add special comparison for null values if a or b can be null ("" is ok)
// toLowerCase() is to compare case-insensitive ('a' != 'A')
if (a.toLowerCase().compareTo(b.toLowerCase()) > 0) {
list.set(i, d);
list.set(i + 1, c);
change = true;
}
}
} while (change);
Sidenote: s.toUpperCase().compareTo(s.toLowerCase()) == 0 would be true if s only contains symbols.
Thanks to everyone for pointing me in the right direction.
One problem was I forgot to .trim() so compareTo wasn't working and neither was comparing with charAt(0).
Also, I found a better implementation of loops for Bubble-Sort.
This is what now works:
String a;
String b;
Person c;
Person d;
for (int i= 0; i< list.size() ; i++){
for(int j=0; j< list.size() - i-1; j++){
a = list.get(j).getLastName().toUpperCase().trim();
b = list.get(j+1).getLastName().toUpperCase().trim();
c = list.get(j);
d = list.get(j+1);
if ( a.compareTo(b) > 0) {
Person temp = d;
list.set(j+1, c);
list.set(j, temp);
}
}
If you write,
for(int j = 0; j < numbers.length; j++)
Then, you will get ArrayIndexOutOfBoundsException for the following line,
tempVar = numbers [j + 1];
Because, the array numbers has length 5 with last index 4 (as index starts from 0). So, when j = 4, the loop breaking condition j < numbers.length or 4 < 5 is true, but you will get exception accessing numbers [4 + 1] index.
So try
for(int j = 0; j < numbers.length -1; j++)
or
for(int j = i; j < numbers.length -1; j++) // more efficient
Now for the second snippet of your code, can you tell me what exactly the problem you get?
From a wild guess, your a.compareTo(b) < 0 is not working like what you want.
Note that compareTo returns a value less than 0 if string a is lexicographically less than the string b.
I'm confused what exactly you want, hence produces the following code which may help you to overcome your problem:
import java.util.ArrayList;
public class Sort{
private static ArrayList<String> list = new ArrayList<String>();
public static ArrayList<String> sortByName(String [] input) {
String temp;
for (int i=0; i< input.length; i++){
for(int j= i; j< input.length-1; j++){
char first = input[i].charAt(0);
char sec = input[j +1].charAt(0);
if (first < sec) {
temp = input[j +1];
input[j +1] = input[i];
input[i] = temp;
}
}
list.add(input[i]);
}
return list;
}
public static void main(String[] args) {
String string[] = {"Ezen", "Allen" , "Wilker", "Kruden", "Crocket"};
bubbleSortByName(string);
}
}
Output is a list containing:
list = [Wilker, Kruden, Ezen, Crocket, Allen]
Bubble Sort Swap Printer in JAVA:
static void countSwaps(int[] a) {
int swaps = 0;
for(int i=0; i<a.length-1; i++){
for(int j=0; j<a.length-i-1; j++){
if (a[j] > a[j+1]){
int temp = a[j];
a[j] = a[j+1];
a[j+1] = temp;
swaps++;
}
}
}
System.out.println("Array is sorted in " + swaps +" swaps.");
}
There is a small problem with the sort program you used originally.
int j=0
should be
int j=i
Also you didn't exactly replace it for string sorting.
a.compareTo(b) < 0
should be
a.compareTo(b) > 0
Check this:
import java.util.*;
public class HelloWorld{
public static void main(String[] args){
ArrayList<Person> list = new ArrayList<Person>();
list.add(new Person("xyz"));
list.add(new Person("abc"));
list.add(new Person("pqr"));
list.add(new Person("lmn"));
String a;
String b;
Person c;
Person d;
for (int i=0; i< list.size(); i++){
for(int j=i; j< list.size()-1; j++){
a = list.get(i).getLastName();
b = list.get(j+1).getLastName();
c = list.get(i);
d = list.get(j+1);
if ( a.compareTo(b) > 0 ) {
Person temp = d;
list.set(j+1, c);
list.set(i, temp);
}
}
}
for(Person person: list){
System.out.println(person.lastName);
}
}
}
class Person{
String lastName;
Person(String str){
lastName = str;
}
public String getLastName(){
return lastName;
}
}
Side notes:
I want to do this through the Array class, rather than ArrayList.
You can assume the Strings within the String array are already organized in proper lexicographical order (alphabetically listed).
For example:
If the array is -> String[] list = {"Bacon","Cheese","Milk","Pancake","Yogurt"};
And I want to add the String "OJ" into the mix it should look like this:
{"Bacon","Cheese","Milk","OJ","Pancake","Yogurt"}
Thanks in advance!
Use java.util.Arrays.binarySearch(...).
You will have to increase the size of the array. This sounds like homework. TreeSet is an easier class to use.
You could append your new entry onto the end of the array and then sort it.
Simple method for insertion sort:
public class InsertionSort {
public static void main(String[] args) {
String[] list = {"Bacon", "Cheese", "Milk", "Pancake", "Yogurt", "OJ"};
InsertionSort in = new InsertionSort();
list = in.insertSort(list);
for (String str : list) {
System.out.println(str);
}
}
public String[] insertSort(String[] list) {
for (int i = 1; i < list.length; i++) {
String val = list[i];
int value = list[i].toLowerCase().charAt(0);
int j = i - 1;
while (j >= 0 && list[j].toLowerCase().charAt(0) > value) {
list[j + 1] = list[j];
j = j - 1;
}
list[j + 1] = val;
}
return list;
}
}
The algorithm taken from here:
public static void insertSort(int[] A){
for(int i = 1; i < A.length; i++){
int value = A[i];
int j = i - 1;
while(j >= 0 && A[j] > value){
A[j + 1] = A[j];
j = j - 1;
}
A[j + 1] = value;
}
}