Quantcast
Channel: Programming Forums
Viewing all articles
Browse latest Browse all 51036

Bubble sort algorithm

$
0
0
Bubble sort to sort an array of string objects. The program fills an array of ten string objects
by reading in user input at the keyboard. I have the following program which compiles but i recieved a java.lang.NullPointerException error when i tried to fill the array object. Could you please tell me where i am going wrong. The error is the below if(condition) line of code but i also posts the whole code. Thanks

 if((yourString[i-1].compareTo(yourString[i-1]))>0)  


  import java.util.*;
public class BubbleSort {
	
	public static void main(String[] args){
		
		Scanner userInput = new Scanner(System.in);
		
		
		String[] arrayStrings = new String[10];
		
		System.out.print("Sorted data: ");
		
		for(int i = 0; i < arrayStrings.length; i++){
			System.out.println(arrayStrings[i]);
			arrayStrings[i] = userInput.nextLine();
			
			bubbleSort(arrayStrings);
			System.out.println(Arrays.toString(arrayStrings));
		}
	}
		
	public static void bubbleSort(String[] yourString){
		
		boolean swap = false;
		do{
			swap = false;
			for(int i = 1; i < yourString.length; i++){			
				
				if((yourString[i-1].compareTo(yourString[i-1]))>0){
					/*first string is greater than second string lexicographically*/
					String s = yourString[i-1];
					yourString[i-1] = yourString[i];
					yourString[i] = s;
					swap = true;
				}//end if
			}//end for
		   }while(swap);
		}
	}//end class  

Viewing all articles
Browse latest Browse all 51036

Trending Articles