Qsort functions and sort functions (carefully reviewed)

Source: Internet
Author: User

First, explain qsort and sort. They can only sort the data in the continuous memory. structures like linked lists cannot be sorted.

First, qsort

Qsort, and unstable ). The qsort function integrated in the C language library function uses a three-way Partitioning Method to Solve the Sorting Problem. The so-called three-way division refers to dividing an array into three parts, which are less than or equal to the value, and greater than the value.

 

Details:-^

Void qsort (void * base, size_t num, size_t width, INT (_ cdecl * compare)

Int compare (const void * elem1, const void * elem2 ));

 

Qsort (that is, quicksort) provides a quick sorting based on the comparison conditions you have given. It mainly uses pointer movement to implement sorting. The sorted result is still in the original array.

The parameters have the following meanings:

The first parameter base is the name of the target array to be sorted (or it can be understood as the address for starting sorting, because an expression like & S [I] can be written)

The second parameter num is the number of target array elements involved in sorting.

The third parameter width is the size of a single element (or the length of each element in the target array). We recommend that you use an expression like sizeof (s [0 ]).

The fourth parameter compare is a comparison function that makes many people feel very confused.

 

Let's briefly discuss the Compare comparison function (writing compare is my personal preference. You can write whatever you like, such as CMP. I will always use CMP for explanation later ).

 

The typical compare definition is int compare (const void * a, const void * B );

The return value must be int, and the two parameters must be of the const void * type. The A and B parameters can be written at will. If the int type is sorted in ascending order, a returns a positive value if A is greater than B. If a is smaller, a negative value is returned. If a is equal, 0 is returned. Other values are sorted in sequence, the following example shows how to sort different types.

 

 

Qsort usage:

I. Sorting int-type Arrays

Int num [100];

Int CMP (const void * a, const void * B)

{

Return * (int *) A-* (int *) B; // sort in ascending order.

// Return * (int *) B-* (int *) A; // sort in descending order

/* Visible: The parameter list is composed of two null pointers. Now it is going to point to your array element. So convert it to your current type and then set the value.

In ascending order, if the value indicated by the first parameter pointer is greater than the value indicated by the second parameter pointer, positive is returned; if the value indicated by the first parameter pointer is equal to the value indicated by the second parameter pointer, zero is returned; if the value indicated by the first parameter pointer is less than the value indicated by the second parameter pointer, a negative value is returned.

In descending order, the opposite is true.

*/

}

Qsort (S, N, sizeof (s [0]), CMP );

 

Complete example function (run on vc6.0 ):

# Include <stdio. h>
# Include <string. h>
# Include <stdlib. h>
Int s [10000], n, I;
Int CMP (const void * a, const void * B)
{
Return (* (int *) B-* (int *) A); // implements descending order.
}
Int main ()
{

// Enter the number of numbers to be entered
Scanf ("% d", & N );
For (I = 0; I <n; I ++)
Scanf ("% d", & S [I]);
Qsort (S, N, sizeof (s [0]), CMP );
For (I = 0; I <n; I ++)
Printf ("% d", s [I]);
Return (0 );
}

2. Sort char array (same as int type)

Char word [100];

Int CMP (const void * a, const void * B)

{

// Note that many online versions are "return * (char *) A-* (int *) B ;"

// Because the editors' inattentive and blind copy are used to upload and upload data, it is always wrong * (int *) B

// It should be return * (char *) A-* (char *) B;

Return * (char *) A-* (char *) B;

}

Qsort (word, 100, sizeof (word [0]), CMP );

// Attachment, which may be applicable to getchar ();

 

3. Sort arrays of the double type (special note)

Double in [100];

Int CMP (const void * a, const void * B)

{

Return * (double *) A> * (double *) B? 1:-1;

// The returned value is obviously an integer returned by CMP. Therefore, to avoid the loss of digits returned by double, use a single value to determine the returned value.

}

Qsort (in, 100, sizeof (in [0]), CMP );

// Appendix: output of the sorting result. It is generally recommended to use the "% G" format.

/* In this example, the output in "% G" format indicates that the system will automatically select a short format in "% F" format and "% E" format, and remove the meaningless 0, but if the system selects "% E", the system will save one-bit output than the "% E" format. (This conclusion comes from the actual operations of vc6.0 )*/

 

4. sorting the struct at a level

Struct in

{

Double data;

Int Other;

} S [100]

 

// Sort by data values from small to large struct. There are many types of sorting key data in the Structure Body. refer to the example above to write

 

Int CMP (const void * a, const void * B)

{

Return (* (in *) a). Data> (* (in *) B). Data? 1:-1;

// Note that this statement may run incorrectly in the vc6.0 environment, but it is not a statement error, but you must build it first or recreate it all. In short, the statement is correct.

// Or you can change the preceding statement to the following three statements.

// Struct in * AA = (in *);
// Struct in * BB = (in *) B;
// Return AA-> DATA> BB-> data? 1:-1;

}

Qsort (S, 100, sizeof (s [0]), CMP );

 

5. List struct

Struct in

{

Int X; // the number of failures.

Int y; // The number of successful attempts.

} S [100];

 

// Sort by X from small to large, and sort by Y when X is equal. As you can imagine, failure is a major cause. The number of failures is less, the number of failures is the same, and the number of successes is more.

 

Int CMP (const void * a, const void * B)

{

Struct in * c = (in *);

Struct in * D = (in *) B;

If (c-> X! = D-> X) return C-> X-D-> X;

Else return D-> Y-C-> Y;

}

Qsort (S, 100, sizeof (s [0]), CMP );

6. Sort strings

Struct in

{

Int data;

Char STR [100];

} S [100];

// Sort the string 'str' in alphabetical order.

Int CMP (const void * a, const void * B)

{

Return strcmp (* (in *) A)-> STR, (* (in *) B)-> Str );

}

Qsort (S, 100, sizeof (s [0]), CMP );

 

Note! CMP in qsort must be written by itself.

 

 

Sort (commonly used in C ++)

When using sort, you must specify using namespace STD; or directly add the # include <algorithm> header file to STD: Sort ().

 

Example:

# Include <iostream>

# Include <algorithm>

Using namespace STD;

 

Int main ()

{

Int A [20];

For (INT I = 0; I <20; ++ I)

Cin> A [I];

 

Sort (A, A + 20); // range. Obviously, this is a + 20 note. This is necessary. If it is a + 19

For (I = 0; I <20; I ++) // The last value of a [19] will not be involved in sorting.

Cout <A [I] <Endl;

Return 0;

}

 

STD: sort is a simplified version of qsort. STD: The sort function is better than qsort in some features: taking nine samples for large arrays, a more complete three-way partitioning algorithm, and more detailed sorting of different array sizes using different methods.

 

 

 

Finally, let's talk about the differences between sort and qsort:

 

Sort is an upgraded version of qsort. If you can use sort as much as possible, it is also relatively simple to use. Unlike qsort, you have to write CMP functions by yourself. You only need to specify the library functions you use, the parameter has only two (for common usage) header pointers and tail pointers;

 

By default, sort is sorted in ascending order. If you want it to be sorted in descending order, you can use your own CMP function.

# Include <iostream>
# Include <algorithm>
Using namespace STD;
Int CMP (int A, int B)
{
If (A <B)
Return 1; // ascending order. If it is changed to A> B, the return value of CMP () in sort () is only 1 and 0, unlike qsort, the-1 !!!!
Else
Return 0;
}


Int main (){
Int I;
Int A [20];
For (INT I = 0; I <5; ++ I)
Cin> A [I];

Sort (A, A + 5, CMP); // range. Obviously, this is a + 5 Note. This is necessary, if it is a + 4, the last value a [4] will not be involved in sorting.
For (I = 0; I <5; I ++)

Cout <A [I] <Endl;
System ("pause ");
Return 0;
}

 

Sort two-dimensional arrays:
# Include <iostream>
# Include <algorithm>
# Include <ctime>
Using namespace STD;

Bool CMP (int * P, int * q)
{
If (P [0] = Q [0])
{
If (P [1] = Q [1])
{
Return P [2] <q [2];
}
Else return P [1] <q [1];
}
Else return P [0] <q [0];
}
Int main ()
{
Srand (time (0 ));
Int I;
Int *** A = new int * [1000];
For (I = 0; I <1000; ++ I)
{
A [I] = new int [3];
A [I] [0] = rand () % 1000;
A [I] [1] = rand () %1000;
A [I] [2] = rand () %1000;
// Printf ("% d \ t % d \ n", a [I] [0], a [I] [1], A [I] [2]);
}
Sort (A, A + 1000, CMP );
/* Cout <"after sort" <Endl;
For (I = 0; I <1000; ++ I)
{
Printf ("% d \ t % d \ n", a [I] [0], a [I] [1], A [I] [2]);
}*/
Return 0;
}

 

So we can also look at C ++.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.