Implementation of the quick select algorithm to find kth smallest number - c

I'm currently working on a program to find the kth smallest number of an array using the quick select algorithm. I've finished it and it works but does not give the correct result every time.
Here's my code (I didn't include my partition or swap algorithm, I'm fairly sure they're correct):
/*
inputs...
*A: pointer to array
n: size of array
k: the item in question
*/
int ksmallest(int *A, int n, int k){
int left = 0;
int right = n - 1;
int next = 1;
return quickselect(A, left, right, k);
}
int quickselect(int *A, int left, int right, int k){
//p is position of pivot in the partitioned array
int p = partition(A, left, right);
//k equals pivot got lucky
if (p - 1 == k - 1){
return A[p];
}
//k less than pivot
else if (k - 1 < p - 1){
return quickselect(A, left, p - 1, k);
}
//k greater than pivot
else{
return quickselect(A, p + 1, right, k);
}
}
Everything compiles fine. I then tried to use the program on the following array: [1,3,8,2,4,9,7]
These were my results:
> kthsm 2
4
> kthsm 1
1
> kthsm 3
2
As you can see, it worked correctly on the 1th smallest item, but failed on the others. What could be the problem? I guessed than my indexing was off but I'm not exactly sure.
EDIT: Added my partition and swap code below, as requested:
int partition(int *A, int left, int right){
int pivot = A[right], i = left, x;
for (x = left; x < right - 1; x++){
if (A[x] <= pivot){
swap(&A[i], &A[x]);
i++;
}
}
swap(&A[i], &A[right]);
return i;
}
//Swaps
void swap(int *a, int *b){
int temp = *a;
*a = *b;
*b = temp;
}

In your partition function the loop condition should be x < right, not x < right - 1.
Also, in the if statements in quickselect, you should switch both uses of p-1 to p. p is already an index and by decreasing k by 1 you turn it into an index(rather than an order) as well. There is no need to decrease p by one again.
int partition(int *A, int left, int right){
int pivot = A[right], i = left, x;
for (x = left; x < right; x++){
if (A[x] < pivot){
swap(&A[i], &A[x]);
i++;
}
}
swap(&A[i], &A[right]);
return i;
}
int quickselect(int *A, int left, int right, int k){
//p is position of pivot in the partitioned array
int p = partition(A, left, right);
//k equals pivot got lucky
if (p == k-1){
return A[p];
}
//k less than pivot
else if (k - 1 < p){
return quickselect(A, left, p - 1, k);
}
//k greater than pivot
else{
return quickselect(A, p + 1, right, k);
}
}
Here's a working example. http://ideone.com/Bkaglb

Related

What's wrong with this quicksort program that I adapted?

edit: added main function
int main(int argc, char *argv[]) {
int arr[] = {3, 2, 1};
int n = sizeof(arr)/sizeof(arr[0]);
quicksort(arr, 0, n-1);
for (int i=0; i<n; i++) {
printf("%3d", arr[i]);
}
return 0;
}
void quicksort(int arr[], int left, int right) {
if (left<right) {
int pivot = partition(arr, left, right);
quicksort(arr, left, pivot-1);
quicksort(arr, pivot+1, right);
}
}
int partition(int arr[], int left, int right) {
/* left to i = smaller than pivot
i+1 = pivot
i+2 to right = bigger than pivot */
int pivot = right, i = left-1;
for (int j=left; j<right-1; j++) { // right-1 because the last num is the pivot
if (arr[j] < arr[pivot]) {
/* j scans the array for values that need to be swapped into the
right side of the partition */
i++;
swap(&arr[j], &arr[i]);
}
// swap pivot into the middle
swap(&arr[i+1], &arr[right]);
}
return i+1; // index of pivot
}
void swap(int *x, int *y)
{
int tmp = *x;
*x = *y;
*y = tmp;
}
I was following a tutorial and tried to translate pseudocode into C but I'm not sure what's wrong with my code
I'm using the input 3,2,1 but its outputting 2 1 3
int partition(int arr[], int left, int right) {
int pivot = right;
int i = left; // <-- set I to left not left -1
for (int j=left; j<right; j++) { // <-- no need for -1 (you already use less and not less or equal operator
if (arr[j] < arr[pivot]) {
swap(&arr[j], &arr[i]); // <-- do the swap first, then increment
i++;
}
}
// swap pivot into the middle
swap(&arr[i], &arr[right]); // <-- this needs to be outside the loop
return i; // <-- return I not I + 1
}

Quicksort implementation in C using first element as pivot

I am a complete beginner to stackoverflow and this is my first post. Please forgive if this is not the correct place to post these kinds of queries. I have written code for the Quicksort algorithm, based on the algorithm given in the Algorithms course in Coursera(It is not for any assignments though).
Basically, there are two functions Quicksort which is called recursively and partition() function that returns the index of the pivot. I select the pivot as the first element of the array every time. I checked the partition() function and it works fine but the array is not sorted even after I call the Quicksort() function.
Any help is appreciated. Thanks.
#include <stdio.h>
void swap(int *p, int i, int j)
{
int temp = *(p+i);
*(p+i) = *(p+j);
*(p+j) = temp;
}
int partition(int *q, int l, int r)
{
int i = l+1, j;
int p = l;
int len = r-l +1;
for (j = l+1; j < len; j++)
{
/*printf("%d \n", j);*/
if ( *(q+j) < *(q+p) )
{
swap(q, i, j);
i += 1;
}
}
swap(q, l, i-1);
/*printf("%d", i-1);*/
return (i-1);
}
void quicksort(int *ptr, int low, int high)
{
if (low < high)
{
int p = partition(ptr, low, high);
printf("%d\n", p);
quicksort(ptr, low, p);
quicksort(ptr, p+1, high);
}
}
int main(){
int i;
int a[] = {3, 8, 2, 5, 1, 4, 7, 6};
int len = sizeof(a)/sizeof(a[0]);
for ( i = 0; i < len; ++i)
{
printf("%d ", a[i]);
}
printf("\n");
int *ptr = a;
quicksort(ptr, 0, len-1);
for (i = 0; i < sizeof(a)/sizeof(a[0]); ++i)
{
printf("%d ", a[i]);
}
printf("\n");
return 0;
}
2 corrections.
Small one: Change 3rd line inside if block in QuickSort function
from
quicksort(ptr, low, p);
to
quicksort(ptr, low, p-1);
This will improve performance.
Main error:
Your partition function is wrong. Specifically the loop where j runs from l+1 to r-l+1, because, r-l+1 can be less than l+1
I'll write the partition function for you if you want (post a comment if you face any problem with that) though I'd advice you to do it yourself.
EDIT:
A possible partition function:
int partition(int *q, int l, int r){
int i,j;
int p = *(q + l);
for(i = l + 1, j = r; ;){
while(*(q + i) <= p)
i++;
while(*(q + j) >= p)
j--;
if(i >= j)
break;
swap(q, i, j);
}
return i;
}
Changes noted in comments.
int partition(int *q, int l, int r)
{
int i = l+1, j;
int p = l;
/* fix: int len = r-l+1; is not used */
for (j = l+1; j <= r; j++) /* fix: j <= r */
{
if ( *(q+j) <= *(q+p) ) /* fix: <= */
{
swap(q, i, j);
i += 1;
}
}
swap(q, l, i-1);
return (i-1);
}
void quicksort(int *ptr, int low, int high)
{
if (low < high)
{
int p = partition(ptr, low, high);
quicksort(ptr, low, p-1); /* optimization: p-1 */
quicksort(ptr, p+1, high);
}
}
If interested, Hoare partition scheme is faster. If you switch to this, don't forget to change the two quicksort calls to quicksort(lo, p) and quicksort(p+1, hi) ). You might want to change the Hoare pivot to pivot = A[(lo+hi)/2], which will avoid worst case issue with sorted or reverse sorted array.
http://en.wikipedia.org/wiki/Quicksort#Hoare_partition_scheme

Quicksort Program not sorting the array

I don't know yet what is the problem with the code:
#include <stdio.h>
#define cutoff 3
int swap(int *x, int *y)
{
int *tmp;
tmp = x;
x = y;
y = tmp;
return *x, *y;
}
void qsort(int a[], int left, int right)
{
int i, j;
int pivot;
if (left + cutoff <= right) // JUST TO ENSURE THAT THE ARRAY'S SIZE IS >= CUTOFF.
{
pivot = median(a, left, right);
i = left;
j = right - 1;
for (;;)
{
while (a[i] < pivot)
i++;
while (a[j] > pivot)
j--;
if (i < j)
swap(&a[i], &a[j]);
else
break;
}
swap(&a[i], &a[right - 1]); // RESTORE PIVOT
qsort(a, left, i-1);
qsort(a, i+1, right);
}
//else
// PERFORM INSERTION SORT
}
void quicksort(int a[], int n)
{
int i;
qsort(a, 0, n - 1);
printf("THE SORTED ARRAY IS: ");
for(i=0;i<n;i++)
printf("%d ", a[i]);
}
int median(int a[], int left, int right)
{
int center = (left + right) / 2;
if(a[left] > a[center])
swap(&a[left], &a[center]);
if(a[left] > a[right])
swap(&a[left], &a[right]);
if(a[center] > a[right])
swap(&a[center], &a[right]);
swap(&a[center], &a[right - 1]); // HIDE PIVOT.
return a[right - 1]; // RETURN PIVOT.
}
void main()
{
int a[100], i, n;
printf("ENTER THE SIZE: ");
scanf("%d", &n);
printf("ENTER THE UNSORTED ARRAY: ");
for (i=0;i<n;i++)
scanf("%d", &a[i]);
quicksort(a, n);
}
The output is the same as teh input and soemtimes it is taking more than the input size. I think that the problem lies in the median function, choosing the pivot.
int swap(int *x, int *y)
{
int *tmp;
tmp = x;
x = y;
y = tmp;
return *x, *y;
}
You're assigning the pointers, not their values. Use this instead
void swap(int *x, int *y)
{
int tmp;
tmp = *x;
*x = *y;
*y = tmp;
}
Also, the return means nothing since the values are swapped by the pointers, and you cannot also return 2 values at a time. The return type should be void like #Yu Hao said
The main problem is in your swap() function
int swap(int *x, int *y)
{
int *tmp;
tmp = x;
x = y;
y = tmp;
return *x, *y;
}
It only swaps the value of the pointer x and y themselves, but not the value that x and y points. Remember that functions in C are always pass-by-value. You need to swap *x and *y.
void swap(int *x, int *y)
{
int tmp;
tmp = x;
*x = *y;
*y = tmp;
}

Segmentation fault while passing array as parameter in c

As an assignment I have to implement mergesort. I am getting segmentation faults as I am passing array as an argument. Everything appears to be correct. I am attaching the code.
arr is int arr[1000], I am passing it to mergesort as
mergesort(arr, 0, n);
Remaining code is as follows.
void merge(int a[], int l, int m, int r)
{
int temp[r -l];
int templ = l;
int tempm = m;
register int k;
for(k=0; k<(r-l); k++)
{
if((tempm >= r)||(templ < m)&&(a[templ] <= a[tempm]))
{ /*if number from left subarray is smaller*/
temp[k] = a[templ];
templ++;
}
else
{ /*number from right subarray is smaller*/
temp[k] = a[tempm];
tempm++;
}
}
for(k= l; k< r; k++)
{ /*copy results back to the array to be returned*/
a[k] = temp[k - l];
}
}
void mergesort(int ar[], int left, int right)
{
int mid;
if(left < right)
{
mid= (left + right)/2;
mergesort(&ar[0], left, mid - 1);
mergesort(&ar[0], mid, right);
merge(&ar[0], left, mid, right);
}
}
Once you have left == 0 and right == 1 in mergesort, you are going to have an infinite recursion:
void mergesort(int ar[], int left, int right) // IF LEFT IS 0 AND RIGHT IS 1 HERE...
{
int mid;
if(left < right) // ...THEN LEFT IS LESS THAN RIGHT AND...
{
mid= (left + right)/2;
mergesort(&ar[0], left, mid - 1);
mergesort(&ar[0], mid, right); // ...HERE WE HAVE A CALL THAT IS
// IDENTICAL TO THE ONE THAT GOT US HERE, INFINITE RECURSION

Writing merge sort in C without pointers

I am trying to write code for homework in C that will take 10 integers from user input into an array and sort it using a recursive merge sort. We have not gone over pointers yet so I wanted to avoid using that in my code (many online examples use pointers).
Here is my code:
/* This code will take input for 10 integers given by the user
into an array, sort them with a recursive merge function
and print the updated array in ascending order. */
#include <stdio.h>
#define ARRSIZE 10
void merge_sort (int arr[], int temp[], int left, int right);
void merge (int arr[], int temp[], int left, int mid, int right);
int main (void){
int arr[ARRSIZE], temp[ARRSIZE], left, right, i;
printf("Enter 10 integers for an array:");
for(i=0;i<ARRSIZE;i++){
printf("\narray value %d:", i+1);
scanf("%d", &arr[i]);
}
left = 0;
right = ARRSIZE-1;
merge_sort(arr, temp, left, right);
printf("\nHere is your updated array:");
printf("\n{");
for(i=0;i<ARRSIZE;i++){
printf("%d,", arr[i]);
}
printf("}");
return 0;
}
void merge_sort (int arr[], int temp[], int left, int right){
if(left<right){
int mid = (right-left)/2;
merge_sort(arr, temp, left, mid);
merge_sort(arr, temp, mid+1, right);
merge(arr, temp, left, mid, right);
}
}
void merge (int arr[], int temp[], int left, int mid, int right){
int i, j, tempi = 0;
for(i=left, j=mid+1; i<=mid && j<=right ;){
// mid+1 is the start of the right array
if(arr[i]<arr[j] && i<=mid){
temp[tempi] = arr[i];
tempi++;
i++;
}
else if(arr[i]>arr[j] && j<=right){
temp[tempi] = arr[j];
tempi++;
j++;
}
}
for(i=0,j=right; i<=j; i++){
arr[i] = temp[i];
}
}
I keep getting a segmentation fault when I run this in my linux shell. Any suggestions?
Well, I've found one subtle bug already: int mid = (right-left)/2; should be int mid = (left+right)/2;
Also, what flows I've found:
You should use tempi = left for simplicity. Simply copy incoming part of array to corresponding part of temporary array.
In your merge cycle, you can place incrementing tempi inside for definition:
for( ...; ...; ++tempi)
Inside that loop you check boundaries AFTER you have read values from that place. This is very bad. VERY. Although, You haven't encounter any problems here just because you are checking boundaries inside for definition :) simply remove them:
for (i = left, j = 1 + mid; i <= mid && j <= right; ++tempi)
{
if (arr[i] < arr[j]) temp[tempi] = arr[i++];
else /* arr[j] <= arr[i] */ temp[tempi] = arr[j++];
}
Cause this loop exits when either subarray has reached end, you have to copy rest of items from another subarray to temp[]:
if (i > mid) i = j; /* if we need to copy right subarray */
for (; tempi <= right; ++tempi, ++i) temp[tempi] = arr[i];
So, your copying back from temporary array will look like
for (i = left; i <= right; ++i) arr[i] = temp[i];

Resources