본문 바로가기
개념공부/C, C++, IDE

qsort

by Zach Choi 2023. 1. 2.
728x90
반응형

This contents is referenced from here : (https://en.cppreference.com/w/c/algorithm/qsort)

 

There is default qsort() function in c and cpp basic library. <stdlib.h>

If you don't have good function for sorting, qsort is great alternatives.

 

  • qsort

- Sorts elements of given array point in ascending order

void qsort(void *ptr, size_t count, size_t size, int (*comp)(const void *, const void *) );
  • parameters

ptr - pointer to the array to sort

count - number of elements in the array

size - size of element in the array in bytes

comp - comparison function which return a negative integer value if the first argument is less than the second,

a positive integer value if the first argument is greater than the second and zero if the arguments are equivalent.

The signature of the comparison function should be equivalent to the following: (User can define)

int cmp(const void *a, const void *b)

The comparison function must not modify the objects passed to it and must return consistent results.

 

Example

 

#include <stdio.h>
#include <stdlib.h>
#include <limits.h>
 
int compare_ints(const void* a, const void* b)
{
    int arg1 = *(const int*)a;
    int arg2 = *(const int*)b;
 
    if (arg1 < arg2) return -1;
    if (arg1 > arg2) return 1;
    return 0;
 
    // return (arg1 > arg2) - (arg1 < arg2); // possible shortcut
    // return arg1 - arg2; // erroneous shortcut (fails if INT_MIN is present)
}
 
int main(void)
{
    int ints[] = { -2, 99, 0, -743, 2, INT_MIN, 4 };
    int size = sizeof ints / sizeof *ints;
 
    qsort(ints, size, sizeof(int), compare_ints);
 
    for (int i = 0; i < size; i++) {
        printf("%d ", ints[i]);
    }
 
    printf("\n");
}

 

  • How to use qsort in 2D array (x Row, 2 Column)

Example in here : (https://stackoverflow.com/questions/17202178/c-qsort-with-dynamic-n-by-2-multi-dimensional-array)

#include <stdio.h>
#include <stdlib.h>

int compare ( const void *pa, const void *pb ) {
    const int *a = *(const int **)pa;
    const int *b = *(const int **)pb;
    if(a[0] == b[0])
        return a[1] - b[1];
    else
        return a[0] - b[0];
}
  
int main(void){
    int **array;
    int number = 10;
    int i;

    array = malloc(number * sizeof(int*));
    for (i = 0; i < number; i++){
        array[i] = malloc(2 * sizeof(int));
        array[i][0] = rand()%20;
        array[i][1] = rand()%20;
    }
    for(i = 0;i < number;++i)
        printf("%2d, %2d\n", array[i][0], array[i][1]);

    printf("\n");

    qsort(array, number, sizeof array[0], compare);

    for(i = 0;i < number;++i)
        printf("%2d, %2d\n", array[i][0], array[i][1]);

    return 0;
}
728x90
반응형