C language sorting algorithm (bubble, selection, fast) method

Source: Internet
Author: User
Tags documentation generator rand sleep

C language sorting algorithm (bubble, selection, fast) method


Comparison of common sorting algorithms

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

Quick sorting algorithm
Algorithm process
Set the array to be sorted to a [0]... A [n-1], first select a data (usually the first data) as the key data, and then put all the numbers smaller than it in front of 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 and j. When the sorting starts: 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 Figure 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 becomes {65 76 97}.

# 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 msn", (double) (end_time1-start_time1)/clocks_per_sec * 1000); // output runtime
# 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 msn", (double) (end_time2-start_time2)/clocks_per_sec * 1000); // output runtime
# 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 msn", (double) (end_time3-start_time3)/clocks_per_sec * 1000); // output runtime
# 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 generated 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 ++) // finds the minimum vertex in the I + 1-n unordered zone and exchanges with arr [I]
           {
If (arr [j] <min)
                 {
Min = arr [j];
Index = j;
                 }  
           }
If (index! = 0) // indicates that the unordered zone has elements smaller than that of 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.

 

 

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.