Fast algorithm with element in the middle as axis

I had to do this little task when I had to sort an array "manually" like quicksort does. There is one particular point (recursive) where I am not sure if my solution is correct. It would be nice if someone could check it out!

Initial sequence: 7 4 6 8 9 1 3 2

Solution (i = left index, x = pivot, j = right index): [Pivot-index = (i + j) / 2]

Sort for positions 0 to 7:

i     x       j
7 4 6 8 9 1 3 2
(swap 8 and 2)

      i       j
7 4 6 8 9 1 3 2

        i   j
7 4 6 2 9 1 3 8
(swap 9 and 3)

          i
          j
7 4 6 2 3 1 9 8

Sort for positions 0 to 5:
i   x     j
7 4 6 2 3 1 9 8
(swap 7 and 1)

  i     j
1 4 6 2 3 7 9 8
(swap 6 and 3)

      i
      j
1 4 3 2 6 7 9 8

Sort for positions 0 to 3:
i x   j
1 4 3 2 6 7 9 8
(swap 4 and 2)

    i
    j
1 2 3 4 6 7 9 8

Sort for positions 0 to 2:
i x j
1 2 3 4 6 7 9 8
(swap 2 'and' 2)

j   i
1 2 3 4 6 7 9 8

Sort for positions 6 to 7 (from first split - not sure here!)

            i j
            x
1 2 3 4 6 7 9 8
(swap 9 and 8)

            j i
1 2 3 4 6 7 8 9

      

Used code:

public class QuickSort {
  public static void sort (int[] a) {       // public method
    quicksort(a, 0, a.length-1);            // starts private method
  }
  private static void quicksort (int[] a, int left, int right) {
    int tmp;                                // temporary param
    int i = left;                           // left index
    int j = right;                          // right index
    int middle = (left + right) / 2;        // middle position
    int x = a[middle];                      // pivot element
    do {
      while (a[i] < x) i++;                 // x works as break
      while (a[j] > x) j--;                 // x works as break
        if (i <= j) {
          tmp = a[i];                       // temporary storage
          a[i] = a[j];                      // a[i] and
          a[j] = tmp;                       // a[j] get swapped
          i++;
          j--;
        }
    } while (i <= j);
                                            // all elements on the left side of the array are smaller than
                                            // all elements in the right side of the array
    if (left < j) quicksort(a, left, j);    // sort left side
    if (i < right) quicksort(a, i, right);  // sort right side
  }
}

      

+3


source to share





All Articles