logo

qsort() v C

qsort() je vnaprej določena standardna funkcija v knjižnici C. To funkcijo lahko uporabimo za razvrščanje matrike v naraščajočem ali padajočem vrstnem redu. Interno uporablja algoritem za hitro razvrščanje, od tod tudi ime qsort. Razvrsti lahko matriko katere koli vrste podatkov, vključno z nizi in strukturami. Deluje dobro in ga je učinkovito izvajati. Obstaja funkcija sort() v C++, podobna qsort() v C. V vidikih, kot so čas delovanja, varnost in prilagodljivost, sort() prekaša qsort().

np.mean

Ta vadnica razlaga funkcijo qsort() s primeri. Standard C ni določil kompleksnosti funkcije, a ker interno sledi algoritmu hitrega razvrščanja, je njena povprečna časovna kompleksnost pogojno vzeta kot O(n*logn). Funkcija je definirana v datoteki glave stdlib; zato ga moramo vključiti pred uporabo.

 #include 

Sintaksa funkcije:

 qsort(array, number, size, function) 

niz : niz, ki ga želite razvrstiti.

število : Število elementov v matriki, ki jih želimo razvrstiti

velikost : Velikost posameznega elementa matrike

funkcijo : Primerjalna funkcija po meri, ki jo moramo napisati v določenem formatu:

ukaz za namestitev npm

Podan format funkcije:

 int compare( const void* a, const void* b) { } 
  • qsort() pokliče funkcijo compare() za vsaka dva elementa v matriki.
  • Argumenta a in b sta dva prazna kazalca, ki kažeta na dva elementa, ki ju je treba primerjati.
  • telo compare() moramo zapisati tako, kot bi moralo vrniti:
    1. 0, če sta dva elementa enaka
    2. -1 ali katero koli drugo negativno celo število, če je prvi element manjši od drugega elementa
    3. 1 ali katero koli drugo pozitivno število, če je prvi element večji od drugega.
  • Ime primerjalne funkcije je lahko poljubno, vendar mora biti ime natančno podano kot argument funkciji qsort().
  • const void* a pomeni, da je a kazalec praznine, katerega vrednost je fiksna. Pred uporabo moramo vtipkati prazen kazalec na neki podatkovni tip.

Zdaj bomo raziskali funkcije za razvrščanje nizov različnih tipov podatkov.

1. Razvrščanje celih števil:

 #include #include int compare(const void* num1, const void* num2) // comparing function { int a = *(int*) num1; int b = *(int*) num2; if(a &gt; b) { return 1; } else if(a <b) { return -1; } 0; int main() arr[50], n, i; printf('enter the size of array to be sorted: '); scanf('%d', &n); printf('
enter elements into array: for(i="0;" i < n; i++) &arr[i]); qsort(arr, sizeof(int), compare); printf('
the sorted printf('
['); if(i="=" n-1) prevent a comma(,) after last element printf('%d', arr[i]); break; printf('%d, ', printf(']'); pre> <p> <strong>Output:</strong> </p> <pre> Enter the size of the array to be sorted: 5 Enter elements into the array: 98 34 89 0 2 The sorted array: [0, 2, 34, 89, 98] </pre> <h3>Understanding:</h3> <p>In these two lines:</p> <p> <strong>int a = *(int*) num1;</strong> </p> <p> <strong>int b = *(int*) num2;</strong> </p> <p>The input array is of type . Hence, we must typecast the void pointers into integer pointers before performing any operations to allocate the required memory. We stored the values the two pointers are pointing at in two other integer variables, a and b. Then, we compared both values using the comparison operators.</p> <p>Instead of using two more temporary variables, we can write a one-line code:</p> <pre> int compare(const void* num1, const void* num2) { return *(int*)a - *(int*)b; } </pre> <ul> <li>If a==b, 0 is returned; if a &gt; b, a positive integer is returned; if a <b, a negative integer is returned.< li> </b,></li></ul> <h3>2. Sorting strings</h3> <pre> #include #include #include int compare(const void* num1, const void* num2) { //char **a = (char**)num1; //char **b = (char**)num2; //return strcmp(*a, *b); return strcmp(*(char**)num1, *(char**)num2); } int main() { int n, i; char* arr[50]; printf(&apos;Enter the size of the array to be sorted: &apos;); scanf(&apos;%d&apos;, &amp;n); printf(&apos;
Enter elements into the array: &apos;); for(i = 0; i <n; i++) { arr[i]="malloc(100*" sizeof(char)); scanf('%s', arr[i]); } qsort(arr, n, sizeof(char*), compare); printf('
the sorted array: '); printf('
['); for(i="0;" i < n; if(i="=" n-1) printf('%s', break; printf('%s, ', printf(']'); pre> <p> <strong>Output:</strong> </p> <pre> Enter the size of the array to be sorted: 5 Enter elements into the array: hi hello how are you The sorted array: [are, hello, hi, how, you] </pre> <h3>Understanding:</h3> <ul> <li>We have an array of strings. The difference between an integer array and a string array is that: <ol class="points"> <li>An integer array is a collection of integers</li> <li>A string array is a collection of character arrays/character pointers.</li> </ol></li> <li>Hence, in the compare function, we need to typecast the void pointers to (char**)a and not (char*)a. <br> <strong>[[string 1], [string 2]?]</strong> <br> When we use char*, it points to the array, and then, to point to a string in the array, we need a double pointer.</li> <li>We used the strcmp() function here. The function is defined in the string.h header file. We need to include it first.</li> <tr><td>The function returns</td> : <ol class="points"> <li>0 if both strings are the same</li> <li>1 if the ASCII value of a character in the string is greater than the corresponding character in the second string</li> <li>-1 if the ASCII value of a character in the string is less than the corresponding character in the second string.</li> </ol> </tr></ul> <h3>3. Sorting an Array of Structure</h3> <pre> #include #include struct Structure { int num1; int num2; }s; typedef struct Structure data; int compare(const void* p, const void* q) { data *a = (data *)p; data *b = (data *)q; int first = (a -&gt; num1)- (b -&gt; num1); int second = (a -&gt; num2)- (b -&gt; num2); if(first == 0) { return second; } return first; } int main() { data array[5]; int i = 0; printf(&apos;Original array: 
&apos;); printf(&apos;[[&apos;); for(i = 0; i <5; i++) { array[i].num1="rand()%10;" array[i].num2="rand()%10;" if(i="=" 4) printf('%d, %d]]', array[i].num1, array[i].num2); break; } %d], [', qsort(array, 5, sizeof(s), compare); printf('
sorted array: 
'); printf('[['); for(i="0;" i < 5; pre> <p> <strong>Output:</strong> </p> <pre> Original array: [[1, 7], [4, 0], [9, 4], [8, 8], [2, 4]] Sorted array: [[1, 7], [2, 4], [4, 0], [8, 8], [9, 4]] </pre> <h3>Understanding:</h3> <p>We declared an array of type Structure, meaning every element in the array is an array of structure elements. In the above program, the structure has two integer elements. The task is to sort the array with respect to the first Structure element, and if any two first elements are equal, we need to sort it using the second element.</p> <p> <strong>Example:</strong> </p> <p>[[1, 2], [3, 4], [1, 4]]</p> <p>Sorted array: [[1, 2], [1, 4], [3, 4]]</p> <p>We used the rand() function to generate random elements in the array. In the compare() function, we need to typecast the two pointers to type structure.</p> <img src="//techcodeview.com/img/c-tutorial/30/qsort-c.webp" alt="qsort() in C"> <p>The specialty of using qsort() is the custom compare function that we can design the way we want. We can also sort a few elements in an array and leave the rest unsorted.</p> <hr></5;></pre></n;></pre></b)>

Razumevanje:

V teh dveh vrsticah:

int a = *(int*) num1;

java primerja nize

int b = *(int*) num2;

Vhodna matrika je vrste . Zato moramo prazne kazalce vtipkati v celoštevilske kazalce, preden izvedemo kakršne koli operacije za dodelitev zahtevanega pomnilnika. Vrednosti, na katere kažeta kazalca, smo shranili v dve drugi celoštevilski spremenljivki, a in b. Nato smo obe vrednosti primerjali s primerjalnimi operatorji.

Namesto da bi uporabili še dve začasni spremenljivki, lahko napišemo enovrstično kodo:

 int compare(const void* num1, const void* num2) { return *(int*)a - *(int*)b; } 
  • Če je a==b, se vrne 0; če je a > b, je vrnjeno pozitivno celo število; če

2. Razvrščanje nizov

 #include #include #include int compare(const void* num1, const void* num2) { //char **a = (char**)num1; //char **b = (char**)num2; //return strcmp(*a, *b); return strcmp(*(char**)num1, *(char**)num2); } int main() { int n, i; char* arr[50]; printf(&apos;Enter the size of the array to be sorted: &apos;); scanf(&apos;%d&apos;, &amp;n); printf(&apos;
Enter elements into the array: &apos;); for(i = 0; i <n; i++) { arr[i]="malloc(100*" sizeof(char)); scanf(\'%s\', arr[i]); } qsort(arr, n, sizeof(char*), compare); printf(\'
the sorted array: \'); printf(\'
[\'); for(i="0;" i < n; if(i="=" n-1) printf(\'%s\', break; printf(\'%s, \', printf(\']\'); pre> <p> <strong>Output:</strong> </p> <pre> Enter the size of the array to be sorted: 5 Enter elements into the array: hi hello how are you The sorted array: [are, hello, hi, how, you] </pre> <h3>Understanding:</h3> <ul> <li>We have an array of strings. The difference between an integer array and a string array is that: <ol class="points"> <li>An integer array is a collection of integers</li> <li>A string array is a collection of character arrays/character pointers.</li> </ol></li> <li>Hence, in the compare function, we need to typecast the void pointers to (char**)a and not (char*)a. <br> <strong>[[string 1], [string 2]?]</strong> <br> When we use char*, it points to the array, and then, to point to a string in the array, we need a double pointer.</li> <li>We used the strcmp() function here. The function is defined in the string.h header file. We need to include it first.</li> <tr><td>The function returns</td> : <ol class="points"> <li>0 if both strings are the same</li> <li>1 if the ASCII value of a character in the string is greater than the corresponding character in the second string</li> <li>-1 if the ASCII value of a character in the string is less than the corresponding character in the second string.</li> </ol> </tr></ul> <h3>3. Sorting an Array of Structure</h3> <pre> #include #include struct Structure { int num1; int num2; }s; typedef struct Structure data; int compare(const void* p, const void* q) { data *a = (data *)p; data *b = (data *)q; int first = (a -&gt; num1)- (b -&gt; num1); int second = (a -&gt; num2)- (b -&gt; num2); if(first == 0) { return second; } return first; } int main() { data array[5]; int i = 0; printf(&apos;Original array: 
&apos;); printf(&apos;[[&apos;); for(i = 0; i <5; i++) { array[i].num1="rand()%10;" array[i].num2="rand()%10;" if(i="=" 4) printf(\'%d, %d]]\', array[i].num1, array[i].num2); break; } %d], [\', qsort(array, 5, sizeof(s), compare); printf(\'
sorted array: 
\'); printf(\'[[\'); for(i="0;" i < 5; pre> <p> <strong>Output:</strong> </p> <pre> Original array: [[1, 7], [4, 0], [9, 4], [8, 8], [2, 4]] Sorted array: [[1, 7], [2, 4], [4, 0], [8, 8], [9, 4]] </pre> <h3>Understanding:</h3> <p>We declared an array of type Structure, meaning every element in the array is an array of structure elements. In the above program, the structure has two integer elements. The task is to sort the array with respect to the first Structure element, and if any two first elements are equal, we need to sort it using the second element.</p> <p> <strong>Example:</strong> </p> <p>[[1, 2], [3, 4], [1, 4]]</p> <p>Sorted array: [[1, 2], [1, 4], [3, 4]]</p> <p>We used the rand() function to generate random elements in the array. In the compare() function, we need to typecast the two pointers to type structure.</p> <img src="//techcodeview.com/img/c-tutorial/30/qsort-c.webp" alt="qsort() in C"> <p>The specialty of using qsort() is the custom compare function that we can design the way we want. We can also sort a few elements in an array and leave the rest unsorted.</p> <hr></5;></pre></n;>

Razumevanje:

  • Imamo niz nizov. Razlika med matriko celih števil in matriko nizov je v tem, da:
    1. Niz celih števil je zbirka celih števil
    2. Niz nizov je zbirka znakovnih nizov/znakovnih kazalcev.
  • Zato moramo v funkciji primerjave vtipkati prazne kazalce na (char**)a in ne (char*)a.
    [[niz 1], [niz 2]?]
    Ko uporabimo char*, kaže na matriko, nato pa za kazanje na niz v matriki potrebujemo dvojni kazalec.
  • Tu smo uporabili funkcijo strcmp(). Funkcija je definirana v datoteki glave string.h. Najprej ga moramo vključiti.
  • Funkcija se vrne:
    1. 0, če sta oba niza enaka
    2. 1, če je vrednost ASCII znaka v nizu večja od ustreznega znaka v drugem nizu
    3. -1, če je vrednost ASCII znaka v nizu manjša od ustreznega znaka v drugem nizu.

3. Razvrščanje niza strukture

 #include #include struct Structure { int num1; int num2; }s; typedef struct Structure data; int compare(const void* p, const void* q) { data *a = (data *)p; data *b = (data *)q; int first = (a -&gt; num1)- (b -&gt; num1); int second = (a -&gt; num2)- (b -&gt; num2); if(first == 0) { return second; } return first; } int main() { data array[5]; int i = 0; printf(&apos;Original array: 
&apos;); printf(&apos;[[&apos;); for(i = 0; i <5; i++) { array[i].num1="rand()%10;" array[i].num2="rand()%10;" if(i="=" 4) printf(\'%d, %d]]\', array[i].num1, array[i].num2); break; } %d], [\', qsort(array, 5, sizeof(s), compare); printf(\'
sorted array: 
\'); printf(\'[[\'); for(i="0;" i < 5; pre> <p> <strong>Output:</strong> </p> <pre> Original array: [[1, 7], [4, 0], [9, 4], [8, 8], [2, 4]] Sorted array: [[1, 7], [2, 4], [4, 0], [8, 8], [9, 4]] </pre> <h3>Understanding:</h3> <p>We declared an array of type Structure, meaning every element in the array is an array of structure elements. In the above program, the structure has two integer elements. The task is to sort the array with respect to the first Structure element, and if any two first elements are equal, we need to sort it using the second element.</p> <p> <strong>Example:</strong> </p> <p>[[1, 2], [3, 4], [1, 4]]</p> <p>Sorted array: [[1, 2], [1, 4], [3, 4]]</p> <p>We used the rand() function to generate random elements in the array. In the compare() function, we need to typecast the two pointers to type structure.</p> <img src="//techcodeview.com/img/c-tutorial/30/qsort-c.webp" alt="qsort() in C"> <p>The specialty of using qsort() is the custom compare function that we can design the way we want. We can also sort a few elements in an array and leave the rest unsorted.</p> <hr></5;>

Razumevanje:

Razglasili smo matriko tipa Structure, kar pomeni, da je vsak element v matriki matrika elementov strukture. V zgornjem programu ima struktura dva celoštevilska elementa. Naloga je razvrstiti matriko glede na prvi strukturni element, in če sta prva dva elementa enaka, jo moramo razvrstiti z uporabo drugega elementa.

primer:

vračanje nizov v javi

[[1, 2], [3, 4], [1, 4]]

Razvrščeno polje: [[1, 2], [1, 4], [3, 4]]

Za ustvarjanje naključnih elementov v matriki smo uporabili funkcijo rand(). V funkciji compare() moramo tipizirati dva kazalca v strukturo tipa.

qsort() v C

Posebnost uporabe qsort() je primerjalna funkcija po meri, ki jo lahko oblikujemo tako, kot želimo. Razvrstimo lahko tudi nekaj elementov v nizu, ostale pa pustimo nerazvrščene.