Skip to content

Quick_Sort #57

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
35 changes: 35 additions & 0 deletions Coding/QuickSort
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
public void quickSort(int arr[], int begin, int end) {
if (begin < end) {
int partitionIndex = partition(arr, begin, end);

quickSort(arr, begin, partitionIndex-1);
quickSort(arr, partitionIndex+1, end);
}
}

private int partition(int arr[], int begin, int end) {
int pivot = arr[end];
int i = (begin-1);

for (int j = begin; j < end; j++) {
if (arr[j] <= pivot) {
i++;

int swapTemp = arr[i];
arr[i] = arr[j];
arr[j] = swapTemp;
}
}

int swapTemp = arr[i+1];
arr[i+1] = arr[end];
arr[end] = swapTemp;

return i+1;
}


TIME COMPLEXITY -
In the best case, the algorithm will divide the list into two equal size sub-lists. So, the first iteration of the full n-sized list needs O(n). Sorting the remaining two sub-lists
with n/2 elements takes 2*O(n/2) each. As a result, the QuickSort algorithm has the complexity of O(n log n).
In the worst case, the algorithm will select only one element in each iteration, so O(n) + O(n-1) + … + O(1), which is equal to O(n2).