Quick Sort Flashcards

1
Q

Quick Sort Definition

A

An algorithm that moves smaller elements to the left of a pivot and larger elements to the right. Then recursively divides the array in 2 partitions

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

Quick Sort complexity

A

Time : Best case O(n log(n))
Worst case O(n^2) if the array is a
already sorted.

Space: O(log(n)) due to recursion

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

Quick sort Function

A

private static void quickSort(int[] array, int start, int end) {
if(end <= start) return;

        int pivot = partition(array, start, end);

        quickSort(array,start,pivot-1);
        quickSort(array,pivot +1, end);
}
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

QS Helper Partition Function

A

private static int partition(int[] array, int start, int end) {
int pivot = array[end];
int i = start -1;

    for(int j = start; j<= end-1; j++){
        if(array[j]  < pivot){
            i++;
            swap(array,i ,j);
        }
    }
    i++;
    swap(array,i ,end);
    return i;
}
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

QS Step1

A

Implement the base case
if(end <= start) return;

Then declare pivot variable that calls the helper class:
int pivot = partition(array, start, end);

Then implement recursion:
quickSort(array,start,pivot-1);
quickSort(array,pivot +1, end);

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

QS Step 2

A

Declare relevant variables for the pivot and indices:
int pivot = array[end];
int i = start -1;

Using a for loop and nested if statement do the comparison and swap:
for(int j = start; j<= end-1; j++){
if(array[j] < pivot){
i++;
swap(array,i ,j);
}
}

Too ensure everything has been compared increment i and do a final swap afte the for loop before returning i:
i++;
swap(array,i ,end);
return i;

How well did you know this?
1
Not at all
2
3
4
5
Perfectly