Bubble sort and quick sort algorithm

Preamble:

A bubble sort algorithm

Two bubble sort program realization

Three quick sort algorithm

Four quick sort algorithm program realization

The first bubble sort algorithm

Brief introduction

Bubble Sort (Bubble Sort), is a computer science simpler sorting algorithm field .

It repeatedly visited elements of the column to sort, in order to compare two adjacent elements, if their order (such as descending, the first letter from A to Z) errors they exchange took over. Working visit element is repeated until there is no need to swap adjacent elements, that is to say the element column has been sorted completed.

The name comes from the fact algorithm larger elements will gradually exchange via a "float" to the top of the column number (ascending or descending order), as if the carbon dioxide bubbles in a carbonated beverage eventually float to the top of the same, hence the name "bubble sort. "

principle

Principle bubble sort algorithm is as follows:

  1. Compare adjacent elements. If the first is greater than the second, the two of them exchanged.

  2. Do the same work for each pair of adjacent elements, from the beginning of the first pair to the end of the last pair. At this point, it should be the last element is the largest number.

  3. Repeat these steps for all elements, except the last one.

  4. Continued to repeat the above steps for each time fewer and fewer elements, a pair of numbers until there is no need to compare.

Analysis of Algorithms

time complexity

If the initial state is the positive sequence file, one pass to complete the order. The number of comparisons required keywords  and record the number of mobile  

Have reached a minimum:

  ,

  。

Therefore, the best bubble sort time complexity is   .
If the original file is in reverse order, the need for

  

Sorting trip. To sort per trip

  

Comparison of times a keyword (1≤i≤n-1), and record each comparison must be moved three times to achieve record exchange position. In this case, the comparison and reached the maximum number of mobile:

The worst time complexity of bubble sort is

  。

 [1]  In summary, therefore the overall average bubble sort time complexity is

  。

Algorithm stability

Bubble sort is the little elements move it forward or backwards in the big elements. Comparison of two adjacent elements is more, also the exchange occurs between these two elements. Therefore, if the two elements are equal, then the exchange will not; if no adjacent two equal elements, even if the front by pairwise exchange the two adjacent up, this time will not be exchanged, the same elements before and after the order has not changed, so the bubble sort is a stable sort algorithm.

The second bubble sort algorithm

C language

#include <stdio.h>
#define ARR_LEN 255 / * maximum length of the array * /
#define elemType int / * Element Type * /
/ * bubble sort * /
/ * 1. From the current element, rearward sequentially comparing each adjacent element, if the reverse switching * /
/ * 2. repeat the above steps for all the elements, until last element * /
/ * elemType ARR []: sorting the target array; int len: the number of elements * /
void bubbleSort (elemType ARR [], int len) {
    elemType TEMP;
    int I, J;
    for (I = 0; I <len-1; I ++) / * the outer loop is to sort the number of laps, the number len for len-1 times * /
        for (J = 0; J <len-. 1-i; J ++) {/ * the inner loop is the number of times per trip comparison, the i-th trip comparator len-i times * /
            IF (ARR [J]> ARR [J + 1]) {/ * comparing adjacent elements, then the switch when the reverse order (greater than the right to the left ascending, descending and vice versa) * /
                TEMP = ARR [J];
                ARR [J] = ARR [J + 1];
                ARR [J + . 1] = TEMP;
            }
        }
}
 
int main (void) {
    elemType arr[ARR_LEN] = {3,5,1,-7,4,9,-6,8,10,4};
    int len = 10;
    int i;
    bubbleSort (arr, len);
    for (i=0; i<len; i++)
        printf ("%d\t", arr[i]);
    putchar ('\n');
    return 0;
}

3 Quick Sorting Algorithm

Quick sort (Quicksort) is an improvement on the bubble sort.

Quick sort proposed by CAR Hoare in 1960. The basic idea is: a trip by ordering the data to be sorted into two independent parts, the part where all the data than the other part of all data to be small, then this method of data for the two parts separately fast sorting, sorting the entire process can be recursively, in order to achieve the whole data into an ordered sequence.

Is provided to sort the array A [0] ...... A [N-1], select any of a first data (the first number is usually chosen array) data as a key, and then all of it is smaller than the number of which are placed in left, all larger than its numbers are put to its right, a process known as a trip to quick sort. It is noteworthy that, quick sort is not a stable sorting algorithm, that is, the same relative positions of the plurality of values ​​may fluctuate at the end of the algorithm.

A trip to quick sort algorithm is:

1) Set two variables i, j, at the beginning of the sort: i = 0, j = N-1;

2) to the first array element as the key data, assigned to Key , i.e. Key = A [0];

3) Search forward starting from j, i.e., starting from the forward search (J,), to find a less than first key value A [j], the A [j] and A [i] value exchange;

4) start from the back search i, i.e., before the start of the backward search (i ++), find the first is greater than the key of A [i], the A [i] and A [j] value exchange;

5) Repeat steps 3 and 4 until i = j; (3,4 step, did not find qualified value, i.e. 3 A [j] is not less than the key , in. 4 A [i] is not greater than the key time changing j, the value of i such that j = j-1, i = i + 1, until you find found qualified value, when the exchange for i, j pointer position unchanged. Further, i == j that process must be exactly the time i + j- or completed, so that at this time the end of the cycle).

Can function qsort () may be ordered array directly in C language. 

usage:

void qsort(void *base, int nelem, int width, int (*fcmp)(const void *,const void *));

Parameters:
  a first address to be sorted array
  2 to be sorted array element number
  3 in the footprint the size of each element
  pointer 4 points a function for sequentially determining an ordering

time complexity

Best-case time complexity of O (nlogn), the process is more complex, it is not repeated here.

Each take the worst case to the number (reference number) is the maximum / minimum value of the current to be compared is, in this case, each time only to obtain a sequence number less than the 1 (i.e., either all larger than the reference number, or smaller than the reference full), then a bubble sort is equivalent, the number of comparisons = (n - 1) + (n - 2) + ... + 2 + 1 = ( n - 1) * n / 2, in this case time complexity is: O (n ^ 2). Usually it appears in the worst case: to be sorted data itself is already a good positive sequence or reverse order row.

Space complexity

  In fact, this is not a good spatial complexity calculation, because some people use non-place sorting, calculated as bad (because some people used the auxiliary array, so it is necessary to calculate the number of your element) ; I will analyze in situ space under quicksort complexity of it;

        First-place quicksort space used is O (1), which is a constant level; and the real space is consumed by recursive calls, because each recursive necessary to maintain some of the data;

     The optimal case space complexity: O (logn); bisects the array each time a case

     The worst case space complexity is: O (n); degenerate case of bubble sort

 

Fourth  quick sort algorithm program realization

The quick sort of faster, because compared to bubble sort, each exchange is leaps and bounds. Every time when sorting a set reference point, the reference point will be less than equal to the number of all placed on the left of the reference point, the reference point will be greater than the number equal to the total reference into the right point. So every time the exchange will not be the same as the bubble sort can only be exchanged between adjacent numbers from the exchange of the big more. Therefore, the total number of comparison and exchange have less natural speed would be increased. Of course, in the worst case, it may still be number two adjacent were exchanged. So the worst time complexity of quick sort and bubble sort is the same is O (N2), its average time complexity of O (NlogN).

Quick sort:
#include <stdio.h>
int A [101], n-; // define global variables, these variables requires the use of two sub-functions in
void quicksort (int left, int right) {
    int I, J, T, TEMP;
    IF (left> right)
        return;
    TEMP = a [left]; // TEMP is stored in the reference number
    I = left;
    J = right;
    the while (! I = J) {// order is important, first from the right to find
        the while (a [J]> = TEMP && I <J)
            J,;
        the while (a [I] <= TEMP && I <J) // find the right
            I ++;       
        IF (I < j) // swap places in the two array numbers
        {
            T = a [I];
            a [I] = a [J];
            a [J] = T;
        }
    }
    // homing reference numbers will eventually
    a [ left] = a [i];
    A [I] = TEMP;
    quicksort (left,. 1-I); // continue processing the left, there is a recursive process
    quicksort (i + 1, right) ; // continue processing the right, there is a recursive process
}
int main () {
    int I;
    // read data
    Scanf ( "% D", & n-);
    for (I =. 1; I <= n-; I ++)
        Scanf ( "% D", & A [I]) ;
    quicksort (. 1, n-); // call quicksort
    after // sorts the output
    for (I =. 1; I <n-; I ++)
        the printf ( "% D", a [I]);
    the printf ( "% D \ n-", A [n-]);
    return 0;
}
 

 

Published 43 original articles · won praise 28 · views 40000 +

Guess you like

Origin blog.csdn.net/u013380694/article/details/90169202