简体   繁体   中英

Null Pointer Exception while trying to Bubble Sort

I'm writing a bubble sort method that involves tokenizing strings and I keep getting a mysterious null pointer exception.

The method takes an array of strings. Each string contains four tokens, last name, first name, social security number and age. The method needs to be able to sort by any of these tokens, so it breaks up each string into tokens, places the tokens in arrays, and then uses bubble sort to sort the tokens, rearranging each string in the array based on the token sorting.

The error occurs when I attempt to split the second string into tokens and save it to an array.

Here's the code.

            for (int i=0; i< array.length;i++) {


              String s1 = sortedArray[i];
              String s2 = sortedArray[i+1];

              String[] holdingArray1;
              String[] holdingArray2;

              holdingArray1 = s1.split("\\s+");
              holdingArray2 = s2.split("\\s+");



              int result = holdingArray1[0].compareTo(holdingArray2[0]);



              if (result > 0)
              {

                  sortedArray[i] = s2;
                  sortedArray[i+1] = s1; 
              }


              System.out.println(sortedArray[i]);
              System.out.println(sortedArray[i+1]);
            }

i may be less than array.length but i+1 may not be. You're assuming there's i+1 elements when you've only checked that there are i elements. Hence, i+1 goes to null and you cannot .split null .

You need to do loop while less than array.length-1 since you are doing sortedArray[i+1].

for (int i = 0; i < array.length-1; i++)
{
  // logic
}

Here is a full bubble sort algorithm example.

    public static int[] bubbleSort(int[] arr, Boolean descending)
    {
         Boolean finished = false;

         while (!finished)
         {
             Boolean held = false;
             int hold;

             for (int i = 0; i < arr.length-1; i++)
             {
                  int curr = arr[i];
                  int next = arr[i+1];
                  Boolean test = curr > next;
                  if (descending) test = curr < next;

                  if (test)
                  {
                     held = true;
                     hold = next;
                     arr[i] = hold;
                     arr[i+1] = curr;
                  }             
             }

             if (!held) finished = true;
          }

          return arr;
     }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM