Results 1 to 5 of 5
Thread: Problem with bubble sort code
 11102010, 05:00 AM #1Member
 Join Date
 Oct 2010
 Posts
 12
 Rep Power
 0
Problem with bubble sort code
The method below for bubble sort should work, it displays the unsorted array fine, but for the sorted array it only displays one of the numbers. It seems to have just skipped over the other elements in the array.
Here is a sample output:
How many random even integers would you like to generate? 6
Unsorted:
196
166
68
14
68
176
Sorted:
196
5
Java Code:public static void bubbleSort (int [] array, int length) { int i, j,t=0; System.out.println("Unsorted: "); for (i=0; i<array.length; i++) { System.out.println(array[i]); } for(i = 0; i < length; i++){ for(j = 1; j < (lengthi); j++){ if(array[j1] > array[j]){ t = array[j1]; array[j1]=array[j]; array[j]=t; } } System.out.println("Sorted: "); for (i=0; i<length1; i++); { System.out.println(array[i]); System.out.println(i); } } }

 11102010, 05:23 AM #3Member
 Join Date
 Oct 2010
 Posts
 12
 Rep Power
 0
 11102010, 09:58 AM #4
 Join Date
 Sep 2008
 Location
 Voorschoten, the Netherlands
 Posts
 13,762
 Blog Entries
 7
 Rep Power
 21
Do you want to print out the 'sorted' array while you are sorting it? i.e. print it out after each sorting step? Note that the last loop also changes the variable 'i' (as the outer loop does). Use another variable for the last loop. btw that variable 'length' is redundant, i.e. your array itself 'knows' its length: array.length. Also what is the semicolon doing here?
Java Code:for (i=0; i<length1; i++);
kind regards,
Jos
 11112010, 04:14 AM #5Member
 Join Date
 Oct 2010
 Posts
 12
 Rep Power
 0
Thanks, i realized after that making a variable for array.length was unnecessary.
The semicolon was a bad typing mistake.
I changed the use of 'i' so that i is declared separatedly within each loop like "for int i" instead of one i used by every loop, and the bubble sort seems to work fine right now.
Thanks Jos.
Similar Threads

Question with bubble sort
By Metastar in forum New To JavaReplies: 22Last Post: 09132010, 07:25 AM 
Bubble sort
By pineapple in forum New To JavaReplies: 3Last Post: 04252009, 01:45 AM 
Trouble w/ Bubble Sort
By bri1547 in forum New To JavaReplies: 4Last Post: 08012008, 05:41 PM 
How to sort a list using Bubble sort algorithm
By Java Tip in forum AlgorithmsReplies: 3Last Post: 04292008, 09:04 PM 
need help with bubble sort
By lowpro in forum New To JavaReplies: 3Last Post: 12172007, 06:27 PM
Bookmarks