Click here to Skip to main content
15,895,746 members
Please Sign up or sign in to vote.
1.33/5 (3 votes)
See more:
C#
package programs;

import java.util.Arrays;

public class bubbleSort {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		
		int[] array={2,3,45,66,4,343,243,452,532,235,6};
		sort(array);
		System.out.println("Sorted Array is "+ " "+Arrays.toString(array));
		

	}

	private static void sort(int[] array) {
		
		if(array==null||array.length<2){
			return;
		}
		int lenthOfArray=array.length;
		for(int i=0;i < lenthOfArray-1;i++){
			if(array[i]>array[i+1]){
				int temp=array[i];
				array[i]=array[i+1];
				array[i]=temp;
			}
			
		}
Posted
Updated 13-Jan-16 5:45am
v2
Comments
ZurdoDev 13-Jan-16 11:31am    
If you debug it, you'll find out what the issue is.
[no name] 13-Jan-16 11:39am    
On a very first glance: You Need to repeat your "for" until no swap is anymore applied.

Have a look to the part "Pseudo code" in Bubble sort - Wikipedia, the free encyclopedia[^]

Hi,

It's not working because the for loop is called only once. Actually, as seen here, on Wikipedia[^], the bubblesort algorithm should run that loop until the array is sorted.

Do you should add a do{...}while(array_not_sorted); and that array_not_sorted is a boolean variable. If in the last iteration you've swapped some elements, the array is not sorted and the do loop should be re-executed, otherwise the array is sorted and both the do and for loop should end. Try to write the code by yourself now ;-)

Hope this helps

LG
 
Share this answer
 
Comments
[no name] 13-Jan-16 11:42am    
Yes! A 5 for you.
LLLLGGGG 13-Jan-16 11:44am    
Thanks! :)
CPallini 13-Jan-16 12:50pm    
5.
I think it is time for you to stop guessing what your code is doing. It is time to see your code executing and ensuring that it does what you expect.

The debugger is your friend. It will show you what your code is really doing.
Follow the execution step by step, inspect variables and you will see that there is a point where it stop doing what you expect.
Mastering Debugging in Visual Studio 2010 - A Beginner's Guide[^]
http://docs.oracle.com/javase/7/docs/technotes/tools/windows/jdb.html[^]
https://www.jetbrains.com/idea/help/debugging-your-first-java-application.html[^]
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900