Sort------------------reference to Geoscience: The Nineth chapter of the data structure of Dahua
1. Basic concepts of sorting
Suppose that the sequence containing n records is {R1,R2,R3,R4,..., rn}, its corresponding keyword is {k1,k2,k3,k4,..., kn}, you need to determine an arrangement of 1,2,3,4,...,n P1,P2,P3,P4,..., PN, To make the corresponding keyword meet
KP1<=KP2<=KP3<=KP4<=....<=KPN (non-descending or non-ascending) relationships, even if the sequence becomes a sequential sequence of keywords {rp1,rp2,rp3,rp4,..., RPN}, such operations are called sorting.
2. internal and external sorting
Sorting is sorted into inner and outer sorts, depending on whether the records to be sorted are all placed in memory.
The inner sort is in the whole process of sorting, all the records to be sorted are placed in memory. The sorting is because the number of records is too large to be placed in memory at the same time, the entire sorting process needs to be exchanged between inside and outside for multiple data.
。 The following is mainly an introduction to the algorithm of the interior sorting.
Performance of internal sorting: Time performance, auxiliary space, complexity of algorithm
The inner sort is divided into insertion sort, exchange sort, select sort, merge sort.
Attention:
The sorted array here starts with the following table 1, and the length of the array is the numeric size calculated from 1.
such as a[1],a[2],a[3],a[4],a[5],a[6],a[7],a[8],..., A[len-1],a[len]
This sort is sorted in ascending order.
3. Bubble sort
Bubble sort is an interchange sort, 22 comparison, if the reverse order is exchanged until there is no reverse sequence. (So a bit of a recursive flavor, in fact, may be for the example of the loop)
A[1],A[2],..., A[len]
Public int[] Mpsort (int a[],int len) {
for (int i=1;i<len;i++)
{
for (int j=i+1;j<=len;j++) {if (a[i]>a[j]) {int temp = A[i]; A[i] = A[j]; a[j] = temp;}}
return A; }
The time complexity of N (n-1)/2, the worst case is O (n^2), the best case only need to compare n-1 times, then is O (n-1)
4. Simple selection Sort
Thought: Through the comparison between the N-i, select the smallest key word record from the n-i+1 record and exchange it with the record of the first (1<=i<=n).
such as i=1, n-1 keyword comparison, from the N-1+1=n record to select the smallest keyword records, and the first I=1 record exchange
i=2, n-2 The second keyword comparison, from the n-2+1= n-1 records to select the smallest key word records, and the i=2 record Exchange
So continue until the i=n-1, 1 keyword comparisons, from n-(n-1) +1=2 records to select the smallest keyword records, and i=n-1 Exchange, thus completing the sorting.
Its time complexity is O (n) selection (1+2+3+...+ (n-1)) = O (n (n-1)/2), the worst case in exchange is n-1 times, preferably 0 times.
void Simpleselect (int []a,int len) {
int i,j,min;
for (i =1;i<len;i++)
{
min = i; for (j=len-i+1;j>=2;j--) {if (A[min]>a[j]) {min = j;}
}//Exchange I and Min's subscript
if (i!=min)
Swap (I,MIN,A);
} }
Or as:
public static void Simpleselect (int []a, int len) {
int i,j,min;
for (i=1;i<len;i++)
{
min = i; for (j=i+1;j<=len;j++) {if (a[min]>a[j]) min =j;}//swap (A,i,min) if (min!=i) {int temp = A[i]; A[i] = A[min]; A[min] = temp; } } }
The difference between a simple sort and a bubble sort (in increments): Bubbles each time the loop as long as the front than the back of the larger, it will be exchanged, and the simple sort is not, it is this I cycle comparison, the smallest value and the first position of the exchange, so simple
It's better to sort than bubble sort. (Time and Space Exchange)
Its time complexity is O (n^2)
5. Direct Insertion Sort
Idea: Insert a record into an ordered table that has been sorted so that a new ordered table with a record number of 1 is added.
void Insertsort (int []a, int len) {
int i=1,j=1;
for (i=2;i<=len;i++)
{
for (j=1;j<i;j++) {if (A[i]<a[j]) {//i is inserted before J, with elements after J and J followed by insert (I,J,A);}
} }
While this can also be achieved by sorting (for the line sequence is from the beginning to judge), but for the advantages of direct insertion sort is not fully utilized, the best case of the above situation will not be expected; The following is a good order from the back start
Judge
void Insertsort (int []a, int len) {
int i,j,temp;
for (i=2;i<=len;i++)
{
if (A[i]<a[i-1]) {temp = A[i]; for (j=i-1;temp<a[j];j--) {a[j+1] = a[j];
A[j+1] =temp;
} } }
In addition, the sequential table is compared from the back forward. In the best case, the data is sorted by itself, so only the time complexity is compared: n-1 = O (n)
The worst-case scenario is reverse, the number of comparisons 1+2+...+n-1=n (n-1)/2, the number of moves 2+3+...+ (n-1) +n = (n-1) (n+2)/2
In general, its time complexity is O (n^2).
The direct insertion sort is better than the bubble sort and the simple selection sort performance. The time complexity for the best performance of bubbling and simple selection sorting is O (n^2), because it is a sequential sequence of sequential operations.
That is, the problem from the messy, began to produce a certain constraint, or the input of the data has a certain characteristics.
6. Hill Sort
To achieve a thought: to make a sequence of records that is based on an increment, and then take the result of a separate direct insertion order within each subsequence is basically ordered rather than locally ordered.
Basic Order: Small keywords basically in front, large basic in the back, a moderate basic in the middle
The basic idea is that the section (similar to the Movement of the window) gradually close to the process, and the interval short points move each other, with the gradual narrowing of the interval, similar data gradually close to each other process.
void Shellsort (int []a, int len)
{
int i,j,temp;
int increment;
increment = Len;
do{
increment = increment/3+1;//increment sequence for (i=increment+1;i<=len;i++)
{
if (A[i]<a[i-increment]) {
temp = A[i];
for (j=i-increment;j>0&&temp<a[j];j-=increment) {
A[j+increment] = A[j];
}
A[j+increment] = temp;
}
}}while (increment>1);
}
The incremental selection here is also tricky. Need to savor.
O (n^1.5), Hill sort is not a stable sort algorithm because it is a jump-type move.
7. Heap Sorting
Heap sort, this is the use of the concept of the big top heap to sort.
The basic idea is to construct a large top heap, swap the root node (maximum) of the large top heap with the last one that is not sorted, the number of unsorted data-1, and then construct the unsorted data into a large heap, until the sequence is completely sorted.
This utilizes the advantages of a complete binary tree, although the data is stored in an array (or linked list) which is actually still using the idea of a complete binary tree, comparing and sorting the
Heap Sort
public static void Heapsort (int []a, int len)
{
int i; First constructs a large top heap for (i= (int) (LEN/2); i>=1;i--) {heapadjust (A,i,len);//heapadjust (Int[]a,int s,int N), A is an array, S is the starting comparison position, N is a number Group size}//Exchange The maximum value, and reconstruct the large top heap for (i=len;i>1;i--) {swap (a,1,i); Heapadjust (a,1,i-1); } }
public static void swap (int a[],int n,int m) {
int temp = A[n]; A[n] = a[m]; A[M] = temp; }
#一种是从最顶层的根节点逐层往下循环
public static void Heapadjust (int []a, int s,int n) {
int i,temp; temp = A[s]; For (I=2*s;i<=n;i *= 2) {if (i<n && a[i]<a[i+1]) i++; if (temp>a[i)) break; A[s] = a[i]; s=i;
} A[s] = temp; }
This begins with the construction of the large top heap, where the data for the root node of each child node is larger than the left and right child nodes. After the large top heap is constructed, after swapping, only the topmost root node is required, and then one of the branches is adjusted to go down until a
Big Top heap.
Swap the maximum value and reconstruct the large top heap, which can also be changed to
for (i=len;i>1;i--) {
Swap (a,1,i);
Heapadjust (a,1,i-1);
}
#HeapAdjust这里的思想是从完全二叉树的最后一个叶子节点的根节点开始向最顶层的根节点循环, although this is the adjustment of all the data, the equivalent of every time the first structure, the exclusion of the position of the line
Other data has been reconstructed again. Efficiency is reduced, and the previous ones are used to meet the needs.
void Heapadjust (int []a,int s,int N) {
int i,j,temp;
for (i= (int) (N-1)/2); i>=1&&j+1<=n;i--) {
j = i*2;
temp = A[j];
if (A[j]<a[j+1]) j + +;
if (Temp<a[j]) a[i] =a[j];
A[J] = temp;
}
}
The algorithm of heap sort is complex: O (n *log N)
8. Merge sort
Thought: Assuming that the initial sequence contains n records, it can be regarded as N ordered subsequence, each subsequence length is 1, then 22 is merged, and the ordered subsequence of the whole length of 2 or 1 is N/2 downward; then cool and cool merge, so, repeat
, until the ordered sequence of length n, this sort method is called the 2-way merge sort.
Note that the merge exit condition is: n==n
SR Merge sort put in TR
Merge sort 1///////////////////////////////////////////////////////
Final static int MAXSIZE = 20;
static int TR2 [] = new int[maxsize+1];
public static int[] Msort (int sr[],int s,int t) {
int m;
if (s==t) tr2[s] = Sr[s]; else{m = (s+t)/2;//Take the whole msort (sr,s,m);//The first half msort (sr,m+1,t);//The second half of the merge (tr2,s,m,t);//merge} return TR2; }
//////////////////////////////////////////////////////////////////////////////////////////////////////////////
First copy the data from the original array to the new array
static int temp_array[] = new int[maxsize+1];
Move S,t, both ends of the data move backwards, because the m,m+1 both ends are already sorted to the order of data, so move the data faster, [s,m][m+1,t]
public static void Merge (int tr[], int s,int m, int t) {
int j,k,i; for (j=m+1,k=s;s<=m&& j<=t;k++) {
if (Tr[s]>tr[j]) {temp_array[k] = tr[j++];} else{temp_array[k] = tr[s++];}
}//Former section if there is any remaining data if (s<=m) for (i=0;i<=m-s;i++) {temp_array[k+i] = tr[s+i];//???} if (J<=t) for (i=0;i<=t-j;i++ {Temp_array[k+i] = tr[j+i];//}//re-pay the temporary array to tr for (i=0;i<tr.length;i++) {tr[i] = temp_array[i];}
Merge sort here is a bit complicated, need to be in the stack more than a few times left the program breakpoint (merge connection point), in Java, if it involves merging, while using the same object parameters, you need to pay attention to the other parameters and the relationship between the object parameters.
The time complexity of the merge sort is O (Nlogn).
At the same time, for recursion, attention is required (1) Recursive exit conditions, (2) recursion if the data volume is large, it is easy to cause stack overflow. A general merge, preferably with a non recursive implementation, because non-recursive does not require more in the stack to keep the appropriate program into
Mouth.
9 Quick Sort
The basic idea is to divide the record into two separate parts, one by one, where all the values are smaller than the values in the other part, and then continue to sort the two parts until the order of all the data is achieved.
public static void QuickSort (int a[],int s,int N) {
if (s>=n) return; Select the middle value, then compare on both sides, the first half is small, the second half to large int mid = Partition (a,s,n); The first half and the latter part are respectively carried out in this sort of QuickSort (a,s,mid-1); QuickSort (A,mid+1,n); }
public static int Partition (int a[],int s,int N) {
int temp = A[s]; while (S<n) {while (s<n && a[n]>temp) n--, swap (a,s,n); while (s<n&& a[s]<temp) s++; Swap (a , s,n);
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