logo

qsort() i C

qsort() er en foruddefineret standardfunktion i C-biblioteket. Vi kan bruge denne funktion til at sortere et array i stigende eller faldende rækkefølge. Den bruger internt hurtigsorteringsalgoritmen, deraf navnet qsort. Det kan sortere et array af enhver datatype, inklusive strenge og strukturer. Det fungerer godt og er effektivt at implementere. Der er en funktion sort() i C++, der ligner qsort() i C. I aspekter som køretid, sikkerhed og fleksibilitet overgår sort() qsort().

Denne vejledning forklarer funktionen qsort() med eksempler. C-standarden specificerede ikke kompleksiteten af ​​funktionen, men da den internt følger hurtigsorteringsalgoritmen, antages dens gennemsnitlige tidskompleksitet foreløbigt at være O(n*logn). Funktionen er defineret i stdlib header-filen; derfor skal vi inkludere det, før vi bruger det.

 #include 

Syntaks for funktionen:

 qsort(array, number, size, function) 

array : Det array, der skal sorteres.

nummer : Antal elementer i arrayet, som vi vil sortere

størrelse : Størrelsen af ​​et individuelt element i arrayet

fungere : Brugerdefineret sammenligningsfunktion, vi skal skrive i et specificeret format:

Specificeret format for funktionen:

 int compare( const void* a, const void* b) { } 
  • qsort() kalder compare()-funktionen for hver to elementer i arrayet.
  • Argumenterne a og b er to tomme pointere, der peger på de to elementer, der skal sammenlignes.
  • vi skal skrive brødteksten af ​​compare() på den måde, den skal returnere:
    1. 0 hvis to elementer er lige store
    2. -1 eller ethvert andet negativt heltal, hvis det første element er mindre end det andet element
    3. 1 eller ethvert andet positivt tal, hvis det første element er større end det andet.
  • Navnet på den sammenlignende funktion kan være hvad som helst, men navnet skal angives nøjagtigt som et argument til qsort()-funktionen.
  • const void* a betyder, at a er en void pointer, hvis værdi er fast. Før vi bruger, skal vi typecaste en void pointer til en eller anden datatype.

Nu vil vi udforske funktionerne til sortering af arrays af forskellige datatyper.

1. Sortering af heltal:

 #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)>

Forståelse:

I disse to linjer:

int a = *(int*) num1;

prøv at fange java

int b = *(int*) num2;

Input-arrayet er af typen . Derfor skal vi typecaste void-pointerne til heltal-pointere, før vi udfører nogen handlinger for at allokere den nødvendige hukommelse. Vi gemte værdierne, de to pointere peger på, i to andre heltalsvariable, a og b. Derefter sammenlignede vi begge værdier ved hjælp af sammenligningsoperatorerne.

I stedet for at bruge yderligere to midlertidige variabler, kan vi skrive en kode på én linje:

 int compare(const void* num1, const void* num2) { return *(int*)a - *(int*)b; } 
  • Hvis a==b, returneres 0; hvis a > b, returneres et positivt heltal; hvis en

2. Sortering af strenge

 #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;>

Forståelse:

  • Vi har en række strenge. Forskellen mellem en heltalsmatrix og en strengmatrix er:
    1. En heltal matrix er en samling af heltal
    2. En string array er en samling af tegn arrays/tegn pointere.
  • Derfor skal vi i sammenligningsfunktionen typecaste void-pointerne til (char**)a og ikke (char*)a.
    [[streng 1], [streng 2]?]
    Når vi bruger char*, peger det på arrayet, og derefter, for at pege på en streng i arrayet, har vi brug for en dobbelt pointer.
  • Vi brugte strcmp()-funktionen her. Funktionen er defineret i string.h header-filen. Vi skal have det med først.
  • Funktionen vender tilbage:
    1. 0 hvis begge strenge er ens
    2. 1, hvis ASCII-værdien af ​​et tegn i strengen er større end det tilsvarende tegn i den anden streng
    3. -1 hvis ASCII-værdien af ​​et tegn i strengen er mindre end det tilsvarende tegn i den anden streng.

3. Sortering af en række af strukturer

 #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;>

Forståelse:

Vi erklærede et array af typen Structure, hvilket betyder, at hvert element i arrayet er et array af strukturelementer. I ovenstående program har strukturen to heltalselementer. Opgaven er at sortere arrayet i forhold til det første strukturelement, og hvis to første elementer er ens, skal vi sortere det ved hjælp af det andet element.

Eksempel:

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

Sorteret array: [[1, 2], [1, 4], [3, 4]]

Vi brugte rand()-funktionen til at generere tilfældige elementer i arrayet. I compare()-funktionen skal vi typecaste de to pointere til typestruktur.

qsort() i C

Specialiteten ved at bruge qsort() er den brugerdefinerede sammenligningsfunktion, som vi kan designe, som vi ønsker. Vi kan også sortere nogle få elementer i et array og lade resten være usorteret.