I've written a partition function for quick sort for an exam online, it passed 6/10 test cases, I dont know which test cases It failed. I'm sharing my code if any one can help me know if there is any problem with my logic.
This is the whole code: https://codebeautify.org/alleditor/cb320209
This is the code for the partition function:
int partition(int arr[], int si, int ei) {
// selecting pivot
int pivot = arr[si];
// finding the pos of the pivot by
// selecting the no of elms lesser to pivot
int newI=si;
for (int i = si; i <= ei; i++) {
if (arr[i] < pivot) {
newI++;
}
}
// swapping pivot with the element which is in its right pos
swap(arr, si, newI);
// making all the elms on right bigger and left smaller
int i = si, j = ei;
while (i < j) {
if (arr[i] < pivot) {
i++;
}
else if (arr[j] > pivot) {
j--;
}
else {
swap(arr, i, j);
i++;
j--;
}
}
return newI;
just a note: when I've changed my partition function with a partition function from geeksforgeeks it passed all the test cases. I'll share that partition function code also(which passed all the test cases).
int partition (int arr[], int low, int high)
{
int pivot = arr[high]; // pivot
int i = (low - 1); // Index of smaller element
for (int j = low; j <= high- 1; j++)
{
// If current element is smaller than or
// equal to pivot
if (arr[j] <= pivot)
{
i++; // increment index of smaller element
swap(&arr[i], &arr[j]);
}
}
swap(&arr[i + 1], &arr[high]);
return (i + 1);
}
Again! I'm sorry but I really dont know in which test cases it failed I just want to know if my logic is right. or i've not done any silly mistake.