Sorting Algorithm Implementation

Source: Internet
Author: User
Document directory
  • Quick Sorting Algorithm

 

The key to implementing these algorithms is to be familiar with the idea of algorithms. In short, Bubble sorting, as the name says, sink the largest number to the bottom after each round of sorting. The idea of sorting is to divide the entire series into ordered and unordered areas. In each round of sorting, the minimum number in the unordered area is moved to the ordered area. The idea of fast sorting is to take a number as the center. Generally, this number is the first number of the series. The whole series is divided into two parts. One part is the area larger than this number, A part is a region smaller than this number. Then sort the series of the two parts separately. If we divide the series into two parts, we can search from the back to the back, and then from the back to the back. For more information, see the documents from Baidu Baike.

From these simple sorting algorithms, there are several features:

Bubble Sorting is the simplest and most stable algorithm.

The selection sorting is not stable, but the efficiency is greatly improved when it is bubble. In fact, in the analysis process, we can find that, compared with the bubble sort, there is a lot less exchange process in the middle and the number of comparisons, which should be the reason for less time. Sorting can be used normally. When the number of comparisons exceeds the unit of ten thousand, it still takes a little time to select sorting.

Fast sorting is said to be the fastest. This can be seen in our thoughts ., When there are many records, the number of comparison cycles in quick sorting is less than that in the previous two. However, this is not the case in the specific implementation process. This is caused by low recursion efficiency. Of course, it is estimated that during the actual use of the process, the rapid sorting estimation will be implemented using the non-recursive operation stack method. This should cause high efficiency and a lot of damage. It is estimated that I will produce a non-Recursive Implementation of quick sorting in the future to truly compare the three of them. In the following program, you can increase the number of N to see the differences between Bubble sorting and selection of sorting performance. When N is small, it cannot be seen when it is about several hundred. When N is large, for example, n = 1000 or N = 10000, the Recursive Implementation of Fast sorting will be stuck there, and no results will be produced.

The specific code is as follows:

/*
** Comparison of common sorting algorithms
*/
# Include <stdio. h>
# Include <stdlib. h>
# Include <time. h>
# Include <windows. h>
# Define N 10
# Define demo 1

Void bubblesort (INT arr [],
Int N );
Void selectsort (INT arr [],
Int N );
Void quicksort (INT arr [],
Int N );
Void printarray (INT arr [],
Int N );
Void generatearray (INT arr [],
Int N );

Int main (INT argc,
Char * argv [])
{
Int arr [N];

Generatearray (ARR, N );
# If demo
Printf ("before the bubble sort ---------------------- \ n ");
Printarray (ARR, N );
# Endif
Printf ("START bubble sort -------------------- \ n ");
Clock_t start_time1 = clock ();
// Start timing
Bubblesort (ARR, N );
Clock_t end_time1 = clock ();
// End Time
Printf ("running time is: % lf Ms \ n", (double) (end_time1-start_time1)/clocks_per_sec * 1000 );
// Output the running time
# If demo
Printf ("after the bubble sort ---------------------- \ n ");
Printarray (ARR, N );
# Endif
Printf ("----------------------------------------------------------- \ n ");

Sleep (1000); // The unit is Millisecond (1‰ seconds)
Generatearray (ARR, N );
# If demo
Printf ("before the selection sort ---------------------- \ n ");
Printarray (ARR, N );
# Endif
Printf ("START selection sort ---------------------- \ n ");
Clock_t start_time2 = clock ();
// Start timing
Selectsort (ARR, N );
Clock_t end_time2 = clock ();
// End Time
Printf ("running time is: % lf Ms \ n", (double) (end_time2-start_time2)/clocks_per_sec * 1000 );
// Output the running time
# If demo
Printf ("after the selection sort ---------------------- \ n ");
Printarray (ARR, N );
# Endif

Printf ("----------------------------------------------------------- \ n ");
Sleep (1000); // The unit is Millisecond (1‰ seconds)
Generatearray (ARR, N );
# If demo
Printf ("before the Quick Sort ---------------------- \ n ");
Printarray (ARR, N );
# Endif
Printf ("START Quick Sort -------------------- \ n ");
Clock_t start_time3 = clock ();
// Start timing
Quicksort (ARR, N );
Clock_t end_time3 = clock ();
// End Time
Printf ("running time is: % lf Ms \ n", (double) (end_time3-start_time3)/clocks_per_sec * 1000 );
// Output the running time
# If demo
Printf ("after the Quick Sort ------------------------ \ n ");
Printarray (ARR, N );
# Endif

System ("pause ");

Return 0;
}

// Generate a random list
Void generatearray (INT arr [],
Int N)
{
Int I;
Srand (unsigned) time (0 ));

For (I = 0; I <n; I ++)
{
Arr [I] = rand ();
// The random number range is between 0 and.
}
}

// Print the list
Void printarray (INT arr [],
Int N)
{
Int I = 0;
For (I = 0; I <n; I ++)
Printf ("% 6D", arr [I]);
Printf ("\ n ");
}

// Classic Bubble Sorting
Void bubblesort (INT arr [],
Int N)
{
Int I = 0, j = 0;
For (I = 0; I <n; I ++)
For (j = 0; j <n-1-I; j ++)
{
If (ARR [J]> arr [J + 1])
{
Arr [J] = arr [J] ^ arr [J + 1];
Arr [J + 1] = arr [J] ^ arr [J + 1];
Arr [J] = arr [J] ^ arr [J + 1];
}
}
}

// Recursive Implementation of quick sorting
Void quicksort (INT arr [],
Int N)
{
If (n <= 1)
Return;

Int I = 0, j = n-1;
Int key = arr [0];
Int Index = 0;

While (I <j)
{
// Search from the back and forward
While (j> I & arr [J]> key)
J --;
If (j = I)
Break;
Else
{
// Exchange a [J] a [I]
Arr [J] = arr [J] ^ arr [I];
Arr [I] = arr [J] ^ arr [I];
Arr [J] = arr [J] ^ arr [I];
Index = J;
}

// Search back and forth
While (I <J & arr [I] <key)
I ++;
If (I = J)
Break;
Else
{
// Exchange a [I] a [J]
Arr [J] = arr [J] ^ arr [I];
Arr [I] = arr [J] ^ arr [I];
Arr [J] = arr [J] ^ arr [I];
Index = I;
}
}
Quicksort (ARR, index );
Quicksort (ARR + index + 1, n-1-index );
}

// Select sorting
Void selectsort (INT arr [],
Int N)
{
Int I, J;
Int min;

For (I = 0; I <n-1; I ++)
{
Int Index = 0;
Min = arr [I];
For (j = I + 1; j <n; j ++)
// Find the least vertex in the I + 1-N unordered zone and exchange it with arr [I]
{
If (ARR [J] <min)
{
Min = arr [J];
Index = J;
}
}
If (index! = 0)
// Indicates that the unordered zone has elements smaller than arr [I ].
{
Arr [I] = arr [I] ^ arr [Index];
Arr [Index] = arr [I] ^ arr [Index];
Arr [I] = arr [I] ^ arr [Index];
}
}
}

 

Note the following points in the program:

I. In a program, I use an exception or to exchange two numbers. This can be based on your preferences. To avoid temporary variables, you can use the following methods to exchange two numbers:

A = a ^ B;
B = a ^ B;
A = a ^ B;

 

Or
A = A + B;
B = A-B;
A = A-B;

The second method is also quite good. The first exclusive or method only applies. If the two numbers are of the int type, A and B can be positive and negative. This does not matter, but must be of the int type.

2. The sleep () function is included in windows. H. Add # include <window. h>

3. For the two srand () seed generator functions of the random number generation function and the rand () random number generator function, refer to the relevant documentation.

4. the demo macro is used to control whether to demonstrate or compare performance. When we adjust n to a small value, for example, 10, we can set demo to 1 to print the array, and we can see the situation before and after comparison. When the N value is adjusted to a large value, for example, 10000, the demo is set to 0, so that the array is not printed and the performance is compared directly.

 

For specific algorithm documentation, refer to the following:

Bubble Sorting

Basic Concepts

The basic concept of bubblesort is to compare two adjacent numbers in sequence, put decimal places in front, and put large numbers in the back. That is, in the first step: first compare the number of 1st and the number of 2nd, and put the decimal number before and after the large number. Then compare the numbers of 2nd and 3rd, place the decimal places before and after the large number, and continue until the last two digits are compared. Place the decimal places before and after the large number. So far, the first stop is over, and the maximum number is placed at the end. In the second round: The comparison starts from the first logarithm (because the number of 2nd is exchanged with the number of 3rd, the number of 1st is no less than 2nd). Before and after placing the decimal number, always compare to the second to the last (the largest position in the last), and the second stop, get a new maximum number at the penultimate position (in fact, it is the second largest number in the entire series ). In this case, repeat the above process until the sorting is completed.

Because the sorting process always places decimal places forward and large numbers backward, it is equivalent to bubbles rising, so it is called Bubble sorting.

It is implemented using a double loop. The External Loop Variable is set to I and the inner loop variable is set to J. The External Loop repeats 9 times, and the inner loop repeats 9, 8,..., 1 time in sequence. The two elements for each comparison are related to the inner loop J, which can be identified by a [J] And a [J + 1] respectively, the values of I are 1, 2 ,..., 9. For each I, j values are 1, 2 ,... 10-i.

Generate

In many program designs, we need to sort a series to facilitate statistics, and Bubble Sorting has always been favored by its concise ideas and methods.

Sorting Process

Imagine the sorted array R [1 .. n] vertical erect, each data element is considered as a bubble with weight, according to the principle that light bubbles cannot be under heavy bubbles, scanning array R from bottom up, when a light bubble that violates this principle is scanned, it is made to "float" up, so it is repeated until the last two bubbles are both light and heavy.

Algorithm example

A [0], a [1], a [2], a [3], a [4], a [5], and a [6]:

49 38 65 97 76 13 27

The first Bubble Sorting Process

38 49 65 97 76 13 27

38 49 65 97 76 13 27

38 49 65 97 76 13 27

38 49 65 76 97 13 27

38 49 65 76 13 97 27

38 49 65 76 13 27 97-this is the result of the first bubble sort.

The second step is to repeat the above process, but it does not need to compare the last 97, because it is already the largest

38 49 65 13 27 76 97-this is the result

The third step continues to repeat, but there is no need to compare the last two.

38 49 13 27 65 76 97

....

Select sort

Basic Ideas

The Direct selection and sorting of files with N records can be directly selected and sorted through n-1 rows to get the ordered results:

① Initial status: the disordered area is R [1. N], and the ordered area is empty.

② Sorting by 1st bits

In the unordered zone R [1 .. n] selects the record R [k] with the minimum keyword, swaps it with the 1st records R [1] In the unordered area, so that R [1 .. 1] and R [2 .. n] into a new ordered area with one more record count and a new unordered area with one fewer record count.

......

③ Sort by I

At the beginning of the I-th sorting, the current ordered and disordered areas are R [1 .. I-1] and R (1 ≤ I ≤ N-1), respectively ). This sort field selects the record R [k] with the smallest keyword from the current unordered area and exchanges it with the R of the 1st records in the unordered area so that R [1 .. i] and R change to a new ordered area with one more record count and a new unordered area with one fewer record count.

In this way, the direct sorting of files with N records can be directly selected through n-1 to obtain the ordered results.

Common sorting methods include simple sorting, tree sorting (tournament sorting), and heap sorting. The preceding algorithm is only a simple step for sorting.

Sorting Process

A [0], a [1], a [2], a [3], a [4], a [5], and a [6]:

49 38 65 97 76 13 27

13 after the first round of sorting [38 65 97 76 49 27]

13 27 after the second sorting [65 97 76 49 38]

13 27 38 after the third round of sorting [97 76 49 65]

13 27 38 49 after the fourth round of sorting [76 97 65]

13 27 38 49 65 after the fifth sorting [97 76]

13 27 38 49 65 76 after the sixth sorting [97]

Last sorting result 13 27 38 49 65 76 97

Algorithm process

Set the array to be sorted to a [0]... A [N-1], first randomly select a data (usually the first data) as the key data, and then put all the smaller than it before it, all the numbers larger than it are placed behind it. This process is called a fast sorting. The quick sorting algorithm is as follows:

1) set two variables I, j, sorting start: I = 0, j = N-1;

2) Take the first array element as the key data and assign it to the key, that is, key = A [0];

3) search forward from J, that is, search forward from the back (j = J-1), find the first value less than the key a [J], and exchange with a [I;

4) Search backward from I, that is, search backward from the beginning (I = I + 1), find the first a [I] greater than the key, and exchange it with a [J;

5) Repeat steps 3rd, 4, 5 until I = J; (Step 4 is not found in the program when J = J-1, I = I + 1 until found. When I is found and switched, the position of the J pointer remains unchanged. In addition, when I = J, the process must be exactly the end of the last loop completed by I + or J +)

For example, the values of array a to be sorted are as follows: (initial key data: x = 49) Note that key x remains unchanged and will always be compared with X, No matter what position, the final goal is to put X in the middle and a small one in front and a large one in the back.

A [0], a [1], a [2], a [3], a [4], a [5], and a [6]:

49 38 65 97 76 13 27

After the first exchange: 27 38 65 97 76 13 49

(Start from the end of step 3 of the algorithm)

After the second exchange: 27 38 49 97 76 13 65

(According to the fourth step of the algorithm, find the value> X from the beginning, 65> 49, the two are exchanged, at this time: I = 3)

After the third exchange: 27 38 13 97 76 49 65

(Follow the fifth step of the algorithm to find the third step for executing the algorithm again.

After the fourth exchange: 27 38 13 49 76 97 65

(According to the fourth step of the algorithm, find the value greater than X from the beginning, 97> 49, exchange the two, at this time: I = 4, j = 6)

At this time, we will find that I = J and end the fast sorting. After a fast sorting, the result is: 27 38 13 49 76 97 65, that is to say, all the numbers greater than 49 are behind 49, so all the numbers smaller than 49 are above 49.

Fast sorting is a recursive call to this process-split the data sequence with 49 as the midpoint and perform similar fast sorting on the previous and subsequent parts respectively to complete the fast sorting of all data sequences, finally, the data sequence is converted into an ordered sequence. According to this idea, the entire process of fast sorting for the preceding array a is shown in 6:

Initial status {49 38 65 97 76 13 27}

After a quick sorting, it is divided into {27 38 13} 49 {76 97 65}

Sort the first and second parts respectively. {27 38 13} after switching between step 3 and Step 4, the parts are sorted by {13 27 38.

{76 97 65} after switching between step 3 and Step 4, it is changed to {65 76 97.

 

From: http://www.cnblogs.com/herbert/archive/2011/01/20/1940392.html

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.