Search code examples
arrayssortinginsertion-sort

Insertion Sort String Array, not sorting right


Hello this is my method for a String Array insertion sort. It is returning bogus results to the console. Mainly just one array element over and over. Any help what needs to be changed is greatly appreciated.Thank you.

 public static void insertionSort(String[] a, int count) {
      int i, j;
      String Value;
      for (i = 1; i < count; i++) {
            Value = a[i];
            j = i - 1 ;
            while (j >= 0 && a[j].compareTo(Value)> 0) {
                  a[j+1] = a[j];
                  j=j-1;
            }
            a[i+1] = Value;

      }
       }

Solution

  • The problem is a[j+1] = a[j];

    Your original a[j+1] would be lost, you just simply replace it, without moving it / storing it, it is just simply replaced by a[j] and get lost...

    I would modify your code like the following: Find the position of current value to be inserted, swap it with the element at that position, then swap back that element into correct position

     public static void insertionSort(String[] a, int count) {
          int i, j;
          String Value;
          for (i = 1; i < count; i++) {
                Value = a[i];
                j = i - 1 ;
                int p = i;
                while (j >= 0 && a[j].compareTo(Value)> 0) {    
                    p = j--;
                }
                // p now is correct position to be inserted
                swap(a[p], a[i]);
                // Now loop the original a[p] back to a[p+1]
                for(int z = i; z > p; z--){
                     swap(a[z], a[z-1]);
                }
          }
     }