Exchange sort bubble sort and quick sort

Source: Internet
Author: User

Exchange sort

The so-called exchange, which is based on the comparison of the two record key values in the sequence of the position of the two records in the sequence, the characteristics of the Exchange order is: A record of large key values to the end of the sequence of movement, the key value of a small record to the front of the sequence movement.

Sort by bubble sort of getting Started

Bubble sort is a typical interchange sorting algorithm. The time complexity of the bubble sort is O (N2), which can be said to be less efficient, but the idea of bubbling sorting is a good introduction to learning sorting algorithms, especially for learning to quickly sort (developed on the basis of bubbling sort).

Basic ideas

The basic idea of bubble sorting is to do (up to) n-1 bubbling, where n is the number of data, where each bubbling will move the unsorted maximum value to the end of the unsorted sequence, bubbling from left to there is a 22 comparison, and a large interchange to the right, with a smaller value moving to the left. Each bubbling will place a maximum value (the unsorted part) in the correct position.

Optimization

The bubbling sort can be optimized: When a trip bubbles, there is no value exchange, the whole sequence is ordered, and we exit the outer loop, and the sort ends.

Source
#include <stdio.h>#include<string.h>#include<stdlib.h>#include<stdbool.h>voidBubble_sort (intValue[],intN) {    inti =0;  for(; i < n-1; i++)//n-1 Trip    {        intj =0; BOOLTag =false;  for(; J < n-i-1; j + +)//22 comparisons in turn        {            if(Value[j] > value[j+1]) {tag=true;//There is an exchange                inttemp =Value[j]; VALUE[J]= Value[j +1]; Value[j+1] =temp; }        }        if(!tag)//There is no exchange, the description is orderly, exiting the loop             Break; } printf ("was ordered%d times \ n", i);}intMain () {intValue[] = {8,6,3,7,4,5,1,2,Ten,9}; intn =Ten;    Bubble_sort (Value,n); printf ("the sort result is: \ n"); inti =0;  for(; I < n;i++) {printf ("%d", Value[i]); } printf ("\ n"); return 0;}

Quick Sort

For an input array with n numbers, a fast sort is a sort algorithm with the worst case time complexity O (n2). Although the worst-case time complexity is poor, fast ordering is often the best choice for an actual sort application because its average performance is very good, its expected time complexity is O (NLGN), and the constant factor is very small.

Fast sorting is one of the most commonly used sorting algorithms in practice, which is fast and high efficiency. Like a name, fast sorting is the best sort of algorithm.

Basic ideas

The idea of fast sequencing is a typical split-rule thought, and the thought of separation and treatment is inseparable from recursion.

The important three steps to divide and conquer the mind is to decompose, resolve, merge

decomposition :

The original problem is decomposed into several sub-problems, which are small instances of the original problem.

Solution :

Solve these sub-problems recursively and solve them directly if the sub-problem is small.

Merge :

Merge the solutions of these sub-problems to obtain the solution of the original problem.

Specific to the fast sorting algorithm, the idea of separation and treatment is embodied.

Decomposition:

Divide the array A[P...R] into two sub-arrays a[p....q-1] and A[Q+1....R], where the elements in a[p....q-1] are not greater than A[Q],A[Q+1....R].

Solve:

By recursive call Quick Sort, sub-array a[p....q-1] and A[Q+1....R] to sort, when the sub-array is empty, or there is only one element, there is no need to recursively solve (this is the problem size is small enough, directly resolved)

Merge:

Since the sub-arrays are sorted by the original address, the original array is ordered after the sub-array is ordered, and no additional merging is required.

Specific details

From the three steps of the above-mentioned quick sorting, the key is to decompose the first step, and the key in decomposition is to determine Q. Let's talk about how to determine Q.

The method for determining Q is this:

First find a principal element (pivot Element), then set two Sentinels, Sentinel I and Sentinel J, Sentinel I pointing to the first element, J pointing to the tail element, Sentinel J from back forward, Sentinel I from the past. What we want to achieve is this: elements larger than the main element are behind the principal, and elements smaller than the main element are in front of the main element. To achieve this, we first compare pivot and a[j] size, if A[J] is greater than pivot, then A[j] does not have to move, when Sentinel J moves forward, that is, j--, know to find a[j] less than pivot, stop. Then compare pivot and A[i], similarly, find a[i] greater than pivot to stop (but I is moving backwards), then swap a[i] and a[j at this time, so the big value goes to the back, and the small value goes to the front. Then repeat the process until the two sentinels meet, namely i=j. You might ask: why start with J instead of I ? This has to do with the position of the pivot you choose, in fact it is possible to start with both I and J, and not too much to see, one of which simplifies the steps. We'll talk about this later. After the final i=j, we also have to arrange pivot position, as for how to arrange behind us.

Instance resolution how to determine the subscript for Q (that is, a value that is larger than the element in the a[p...q-1], which is smaller than the element in the A[Q+1...R]

Here's an example of how to find Q

There is such a sequence:

1, suppose we choose pivot is 8,pivot this thing is casually selected (also not, a bad pivot will affect the efficiency of fast sorting, but that is something, is the problem of optimization). The reason for choosing 8 is that it is easier to work on both ends (and why, at the end of the story, a pivot is chosen anyway).

Sentinel I points to 8,j pointing to 9, as

2, then, we start with J, from the back forward, to find a smaller than the value of 8 to stop, that is, J stop in the position of 0 (as for why start from J, back to talk)

3, then we start from I, find the value than 8 to stop, we found that we know that I=j also did not find a value than 8, we also said before the Sentinel meet to terminate, so there are

It was supposed to have the values of I and J exchanged, and then repeat the 2,3 process until i=j, because I chose this sequence not particularly good, the first time to i=j (no matter, we will randomly select a pivot), this time we want to exit the loop, and then arrange the pivot position. For this pivot selection on the far left, and first starting with J, the value of 8 and I is exchanged directly (also the value of J), and then return I, is the Q we asked. The two sub-arrays that are decomposed are [0,6,3,7,4,5,1,2] and [9]. The two arrays are then recursively sorted.

Note that the direct interchange assumes that pivot selects the leftmost value, and each time it starts at the back end (the J-end) . The different pivot selection methods, starting with I or starting with J, affect how the final pivot is allocated. Here are a few things to look at.

We'll start with the J-end, so we'll see what happens next from I.

First we still select the leftmost 8 for pivot,i pointing to the leftmost, j pointing to the right,

Then we start at the left (i) and go backwards until we find a value greater than 8 and finally find 9, which I and J also met.

After the Sentinels meet, we want to assign pivot, in the last case, we are directly exchanging the value of I and 8, but this time if we directly exchange the value of I, and then return I as the Q we have obtained, the result is wrong.

So what's the right thing to do? should be swap 9 left of 0 and pivot, i.e. swap 0 and 8

Why does it cause this kind of result? As mentioned earlier, the final pivot allocation problem, with two points, one is the choice of pivot, the second is from the I-end or from the J-end. Pivot selection at the far left, we have to pay attention to the left side of this position is very special, special is that: This position must be placed in a smaller than pivot value, unless a[p...q+1] This sub-array is empty (at this point should be placed pivot), think about it. So what's the difference between starting from I and starting with J first? we have to notice that starting from I is looking for values greater than pivot and then stopping, and starting with J is looking for values smaller than pivot and then stopping, so if I start with I, when I and J meet, the value of the meeting must be greater than pivot (like 9). Conversely, if starting with J, the value of the meeting place must be less than pivot (for example, 0 of the first case). When the value of the encounter is less than pivot, the value of the pivot and meeting place is exchanged directly. However, if the value of the meeting place is greater than pivot, this time cannot be exchanged directly, the direct exchange will not meet the conditions, should be exchanged pivot and the first bit of the meeting place value .

Next, we select a pivot that is not on the left-hand side, for example, we choose 4.

This time we chose to start with the I, to find a value that is larger than 4 and then stop and stop at 8. Then, starting with J, we find a value that is smaller than 4 and stops at 0.

Exchange values at I and J

Then start the next round, that is, starting from I to find a number larger than 4, stop, stop at 6, and then from the beginning of J to look forward than 4 small number, stopped at 2.

Exchange the values at I and J.

Then started the next round, starting with I, stopped at 7, and stopped at 1 from J.

Exchange values at the I and J

Then start the next round, from I to the back, stop at 5, and then from J to find the value of less than 4, when to 5, J and I meet. When we meet, we're going to assign pivot values.

We found that the value of the meeting place is greater than pivot (4), so this time we want to exchange 4 and 5 front (that is, 4) value, this good (coincidentally) pivot is 5 of the previous, so do not exchange. Then we return to I-1, which is the Q we have obtained. The two arrays that are decomposed are [0,2,3,1] and [5,7,6,8,9]

Let's just keep writing about it, let's solve [0,2,3,1] first.

in order to finally allocate pivot simply, we select the leftmost value as pivot and start with J every time .

From J onwards, find values less than 0, stop at 0, and I meet, exchange the value of the meeting place (0) and pivot (0) (is the same)

Returns the value of I, which is the Q we have obtained, two sub-arrays, [] and [2,3,1]

Then we deal with [2,3,1]

Starting from J, stop at 1 and stop at 3 from I

Value Exchange

And then start a new round, starting with J, met I stop, assign pivot

Exchange values at pivot and I

Return I, that is, the Q, two arrays of [1] and [3], there is only one value end.

Back, we solved [7,6,8,9]

I believe you have already understood,,,,, did not write .....

Finally, give the code
#include <stdio.h>#include<stdlib.h>intPartitionintValue[],intStartintend) {         intPivot = Value[start];//Pivot selects the value at the leftmost end         inti =start; intj =end;  while(I! =j) {if(Value[j] >= pivot)//start with the J first .{J--; Continue; }                  if(Value[i] <=pivot) {i++; Continue; }                  //Exchange values at I and J                  inttemp =Value[i]; Value[i]=Value[j]; VALUE[J]=temp; }         //exchanging values for pivot and meeting places         inttemp =Value[start]; Value[start]=Value[i]; Value[i]=temp; //return to the subscript of the meeting place         returni; }voidQuick_sort (intValue[],intStartintend) {         if(End-start +1<=1)//when an array is empty or has only one element, it is not sorted                  return; intQ = partition (value,start,end);//Find Q//two sub-arrays decomposed by recursive solutionQuick_sort (Value,start,q-1); Quick_sort (Value,q+1, end); }  intMain () {intValue[] = {8,6,3,7,4,5,1,2,0,9}; intn =Ten; Quick_sort (Value,0,9); printf ("the sort result is: \ n"); inti =0;  for(; I < n;i++) {printf ("%d", Value[i]); } printf ("\ n"); return 0;}

Finally attach Word document and source code file

Link: http://pan.baidu.com/s/1slLkPFf Password: Mnoi

If you feel that it is useful to you, please order a praise ~ ~ ~

Exchange sort bubble sort and quick sort

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.