Application and Performance Comparison of sort and qsort Functions

Source: Internet
Author: User

Sort

Template <class ranit>

Void sort (ranit first, ranit last );

 
Template <class ranit, class Pred>
Void sort (ranit first, ranit last, PRED Pr );
The first template function reorders the sequence designated by iterators in
The range [first, last) to form a sequence order by operator <. Thus, the elements are sorted in ascending order. (Ascending Order ).

The function evaluates the ordering predicate x <Y at most
Ceil (last-first) * log (last-first) times. Time Complexity: N * log (n ).

The second template function behaves the same, doesn't that it replaces
Operator <(x, y) with PR (x, y ).

In fact, STD: sort is a simplified version of qsort. By analyzing STD: sort, we can understand the advantages and disadvantages of the qsort function, so that we can better understand the nature of the qsort function and understandAlgorithmThoughts.

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.



# Include <ctime>
# Include <algorithm>
Using namespace STD;
Int main ()
{
Int Val [50];
Srand (Time (null ));
For (INT I = 0; I <50; I ++)
{
Val [I] = rand () %100;
Cout <Val [I] <Endl;
}
Cout <"output after sorting:" <Endl;
Sort (Val, Val + 50 );
For (I = 0; I <50; I ++)
{
Cout <Val [I] <Endl;
}
Return 0;
};


2. qsort


Quick sorting is a recursive process. Each time a series is processed, a number is selected from the series as the score. Then, in the series, move the number with a small score to the left of the score, and move the number with a large score to the right of the score. After such processing, the number is determined at the position of the final sorted series. Then

We treat a number smaller than this number and a number larger than this number as two subsequences respectively to call the next recursion, and finally obtain

Sorted series. The above describes the basic fast sorting method. Each time an array is divided into two points and a score in the middle, the basic sorting efficiency is low for arrays with multiple duplicate values. The qsort function integrated in the C language library function uses a three-way division method to solve this 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.


Qsort is included in the stdlib. h header file. The function has four parameters and does not return values. A typical qsort statement is as follows:
Qsort (S, N, sizeof (s [0]), CMP); the first parameter is the name of the array involved in sorting (or it can be understood as the address for starting sorting, because the expressions like & S [I] can be written, this problem is described below );
The second parameter is the number of elements involved in sorting;
The third three numbers are the size of a single element. We recommend that you use an expression like sizeof (s [0, the fourth parameter is a very confusing comparison function. It is troublesome to talk about this function...
We will discuss the CMP comparison function (writing CMP is my personal preference, and you can write whatever you like, such as qcmp). The typical definition of CMP is:
Int CMP (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 are anything I want to write. 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. in the function body, a and B must be forcibly converted to obtain the correct return value. Different types have different processing methods.
For more information, see the examples below.
1. fast sorting is unstable. This instability is manifested in the uncertainty of the time it is used. The best case is (O (n )) it is too different from the worst case (O (N ^ 2). We generally say that O (nlog (N) refers to its average time.
2. fast sorting is unstable. This instability occurs when the comparison elements of the same sequence are different. Suppose we have such a sequence: 3, 3, 3, however, there is a difference between the three. We mark them as 3A, 3B, and 3c. the result after the fast sorting is not necessarily 3A, 3B, or 3C, so in some special cases, we must use struct to make it stable (the example of No. 6 illustrates this problem)
3. the two parameters of the comparison function must be const void *. Note that writing A and B is just my personal preferences, and writing CMP is just my personal preferences. we recommend that you redefine two pointers in CMP to force type conversion, especially when sorting the struct.
4. the third parameter of qsort, sizeof, is recommended to use sizeof (s [0]). Especially for struct, we often define 2 * sizeof (INT) this will cause problems. Using sizeof (s [0) is both convenient and safe.
5. if you want to partially sort the array, for example, to arrange M elements starting from S [I] in an array of S [N, you only need to modify the first and second parameters: qsort (& S [I], M, sizeof (s [I]), CMP );
No.1. manual Implementation of quicksort
# Include <stdio. h>
Int A [100], n, temp;
Void quicksort (int h, int T)
{
If (h> = T) return;
Int mid = (H + T)/2, I = H, J = T, X;
X = A [Mid];
While (1)
{
While (A [I] <X) I ++;
While (A [J]> X) j --;
If (I> = J) break;
Temp = A [I];
A [I] = A [J];
A [J] = temp;
}
A [Mid] = A [J];
A [J] = X;
Quicksort (H, J-1 );
Quicksort (J + 1, t );
Return;
}
Int main ()
{
Int I;
Scanf ("% d", & N );
For (I = 0; I <n; I ++) scanf ("% d", & A [I]);
Quicksort (0, n-1 );
For (I = 0; I <n; I ++) printf ("% d", a [I]); Return (0 );
}

No. 2. Sort the int array most commonly.
# Include <stdlib. h>
# Include <ctime>
Int CMP (const void * a, const void * B)
{
Return (* (int *) A-* (int *) B );
// If (* (int *) A> * (int *) B)
// Return 1;
// Else if (* (int *) A = * (int *) B)
// Return 0;
// Else
// Return-1;
}
Int main ()
{
Int A [50];
Srand (Time (null ));
For (INT I = 0; I <50; I ++)
{
A [I] = rand () %100;
Cout <A [I] <Endl;
}
Qsort (A, 50, sizeof (INT), CMP );
Cout <"output after fast sorting:" <Endl;
For (Int J = 0; j <50; j ++)
Cout <A [J] <Endl;
Return 0;
}
No. sorts arrays of the double type. The principle is the same as that of Int. This is because it is necessary to judge that if a = B returns 0, but strictly speaking, the two double numbers cannot be equal, it can only be said that FABS (a-B) <1e-20 and so on, so here only 1 and-1 are returned.
# Include <stdio. h>
# Include <stdlib. h>
Double S [10];
Int I, N;
Int CMP (const void * a, const void * B)
{
Return (* (double *) A-* (double *) B> 0 )? 1:-1 );
}
Int main ()
{
Scanf ("% d", & N );
For (I = 0; I <n; I ++)
Scanf ("% lf", & S [I]);
Qsort (S, N, sizeof (s [0]), CMP );
For (I = 0; I <n; I ++)
Printf ("% lf", s [I]);
Return (0 );

}
No. 4. Sort a character array. The principle is the same as that of Int.
# Include <stdio. h>
# Include <string. h>
# Include <stdlib. h>
Char s [10000], I, N;
Int CMP (const void * a, const void * B)
{
Return (* (char *) A-* (char *) B );
}
Int main ()
{
Scanf ("% s", S );
N = strlen (s );
Qsort (S, N, sizeof (s [0]), CMP );
Printf ("% s", S );
Return (0 );
}
No. 5. comment out the sorting of struct. most of the time, we sort the struct, such as the cherry blossom in the qualifying match. Generally, the type is forcibly converted in the CMP function at this time. Do not convert it in the return function, I can't tell why, Program It will be clearer, and it is absolutely correct. Here, pay attention to the problem that double returns 0.
# Include <stdio. h>
# Include <stdlib. h>
Struct Node
{
Double date1;
Int no;
} S [100];
Int I, N;
Int CMP (const void * a, const void * B)
{
Struct node * AA = (node *);
Struct node * BB = (node *) B;
Return (AA-> date1)> (bb-> date1 ))? 1:-1 );
}
Int main ()
{
Scanf ("% d", & N );
For (I = 0; I <n; I ++)
{
S [I]. No = I + 1;
Scanf ("% lf", & S [I]. date1 );
}
Qsort (S, N, sizeof (s [0]), CMP );
For (I = 0; I <n; I ++)
Printf ("% d % lf/N", s [I]. No, s [I]. date1 );
Return (0 );

}
No.6. sort the struct. add no to make it stable (that is, when the data value is equal, it is arranged in the original order)

# Include <stdio. h>
# Include <stdlib. h>

Struct Node
{
Double date1;
Int no;
} S [100];
Int I, N;
Int CMP (const void * a, const void * B)
{
Struct node * AA = (node *);
Struct node * BB = (node *) B;
If (AA-> date1! = BB-> date1)
Return (AA-> date1)> (bb-> date1 ))? 1:-1 );
Else
Return (AA-> NO)-(bb-> NO ));
}
Int main ()
{
Scanf ("% d", & N );
For (I = 0; I <n; I ++)
{
S [I]. No = I + 1;
Scanf ("% lf", & S [I]. date1 );
}
Qsort (S, N, sizeof (s [0]), CMP );
For (I = 0; I <n; I ++)
Printf ("% d % lf/N", s [I]. No, s [I]. date1 );
Return (0 );
}
No. 7. Sorting string arrays (char s [] [] type)

# Include <stdio. h>
# Include <string. h>
# Include <stdlib. h>

Char s [1, 100] [2, 100];
Int I, N;
Int CMP (const void * a, const void * B)
{
Return (strcmp (char *) A, (char *) B ));
}
Int main ()
{
Scanf ("% d", & N );
For (I = 0; I <n; I ++)
Scanf ("% s", s [I]);
Qsort (S, N, sizeof (s [0]), CMP );
For (I = 0; I <n; I ++)
Printf ("% s/n", s [I]);
Return (0 );
}

No. 8. Sort string arrays (char * s [] type)
# Include <stdio. h>
# Include <string. h>
# Include <stdlib. h>

Char * s [100];
Int I, N;

Int CMP (const void * a, const void * B)
{
Return (strcmp (* (char **) A, * (char **) B ));
}

Int main ()
{
Scanf ("% d", & N );
For (I = 0; I <n; I ++)
{
S [I] = (char *) malloc (sizeof (char *));
Scanf ("% s", s [I]);
}
Qsort (S, N, sizeof (s [0]), CMP );
For (I = 0; I <n; I ++) printf ("% s/n", s [I]);
Return (0 );
}



Use of bsearch functions:

Bsearch

@ Import URL (MS-ITS: dsmsdn. chm:/html/msdn_ie4.css );

Performs a binary search of a sorted array.

Void * Bsearch ( Const Void
*Key, Const Void *Base,
Size_t
Num, Size_t Width, Int (
_ Cdecl *Compare )( Const Void
*Elem1, Const Void *Elem2
) );


Bsearch

@ Import URL (MS-ITS: dsmsdn. chm:/html/msdn_ie4.css );

Return Value

BsearchReturns a pointer to an occurrenceKeyIn the Array
Pointed toBase. IfKeyIs not found, the function returns
Null. If the array is not in ascending sort order or contains duplicate
Records with identical keys, the result is unpredictable.

Parameters

Key

Object To search

Base

Pointer to base of search data

Num

Number of Elements

Width

Width of Elements

Compare

Function that compares two elements:Elem1And
Elem2

Elem1

Pointer to the key for the search

Elem2

Pointer to the array element to be compared with the key


# Include <stdlib. h>
# Include <ctime>
# Include <search. h>

Int CMP (const void * a, const void * B)
{
Return (* (int *) A-* (int *) B );
}

Int main ()
{
Int A [50];
Srand (Time (null ));
For (INT I = 0; I <50; I ++)
{
A [I] = rand () %100;
Cout <A [I] <Endl;
}

Qsort (A, 50, sizeof (INT), CMP );
Cout <"output after fast sorting:" <Endl;
For (Int J = 0; j <50; j ++)
Cout <A [J] <Endl;

Int * loc = 0;
Int A = 3;
Loc = (int *) bsearch (& A, A, 50, sizeof (INT), CMP );
Cout <"the value address is:" <Endl;
Cout <loc <Endl;

Return 0;
}

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.