Javatpoint Logo
Javatpoint Logo

Quick Sort

Quick sort is the widely used sorting algorithm that makes n log n comparisons in average case for sorting of an array of n elements. This algorithm follows divide and conquer approach. The algorithm processes the array in the following way.

  1. Set the first index of the array to left and loc variable. Set the last index of the array to right variable. i.e. left = 0, loc = 0, en d = n - 1, where n is the length of the array.
  2. Start from the right of the array and scan the complete array from right to beginning comparing each element of the array with the element pointed by loc.
  3. Ensure that, a[loc] is less than a[right].

    1. If this is the case, then continue with the comparison until right becomes equal to the loc.
    2. If a[loc] > a[right], then swap the two values. And go to step 3.
    3. Set, loc = right
  1. start from element pointed by left and compare each element in its way with the element pointed by the variable loc. Ensure that a[loc] > a[left]
    1. if this is the case, then continue with the comparison until loc becomes equal to left.
    2. [loc] < a[right], then swap the two values and go to step 2.
    3. Set, loc = left.

Complexity

Complexity Best Case Average Case Worst Case
Time Complexity O(n) for 3 way partition or O(n log n) simple partition O(n log n) O(n2)
Space Complexity O(log n)

Algorithm

PARTITION (ARR, BEG, END, LOC)

  • Step 1: [INITIALIZE] SET LEFT = BEG, RIGHT = END, LOC = BEG, FLAG =
  • Step 2: Repeat Steps 3 to 6 while FLAG =
  • Step 3: Repeat while ARR[LOC] <=ARR[RIGHT]
    AND LOC != RIGHT
    SET RIGHT = RIGHT - 1
    [END OF LOOP]
  • Step 4: IF LOC = RIGHT
    SET FLAG = 1
    ELSE IF ARR[LOC] > ARR[RIGHT]
    SWAP ARR[LOC] with ARR[RIGHT]
    SET LOC = RIGHT
    [END OF IF]
  • Step 5: IF FLAG = 0
    Repeat while ARR[LOC] >= ARR[LEFT] AND LOC != LEFT
    SET LEFT = LEFT + 1
    [END OF LOOP]
  • Step 6:IF LOC = LEFT
    SET FLAG = 1
    ELSE IF ARR[LOC] < ARR[LEFT]
    SWAP ARR[LOC] with ARR[LEFT]
    SET LOC = LEFT
    [END OF IF]
    [END OF IF]
  • Step 7: [END OF LOOP]
  • Step 8: END

QUICK_SORT (ARR, BEG, END)

  • Step 1: IF (BEG < END)
    CALL PARTITION (ARR, BEG, END, LOC)
    CALL QUICKSORT(ARR, BEG, LOC - 1)
    CALL QUICKSORT(ARR, LOC + 1, END)
    [END OF IF]
  • Step 2: END

C Program

Output:

The sorted array is: 
23
23
23
34
45
65
67
89
90
101

Java Program

Output:

The sorted array is: 
23
23
23
34
45
65
67
89
90
101

C# Program

Output:

The sorted array is: 
23
23
23
34
45
65
67
89
90
101

Next TopicRadix Sort




Please Share

facebook twitter google plus pinterest

Learn Latest Tutorials


Preparation


B.Tech / MCA