Internal sorting method diagram and code

Internal sorting method diagram and code

1. Direct insertion sort

Direct insertion sort is a simple sorting method. The specific method is: when inserting the i-th record, R1, R2,..., Ri-1 are already sorted, and then the keyword Ki of Ri is followed by the keyword Ki -1, Ki-2, etc. are compared to find out the position that should be inserted and insert Ri. The insert position and the following records move backward in turn.

Insert sort diagram directly

void Insertsort(int data[],int n)
/*将数组data[0]~data[n-1]中的n个整数按非递减有序的方式进行排列*/
{
int i,j;
int tmp;
for(i=1;i<n;i++)
  if(data[i]<data[i-1]){
    tmp=data[i];
    data[i]=data[i-1];
    for(j=i-1;j>=0&&data[j]>tmp;j--)
      data[j+1]=data[j];
    data[j+1]=tmp;
  }
}

2. Bubble sort

The method of bubble sorting for n records is: first compare the key of the first record with the key of the second record, if it is in the reverse order, exchange the values ​​of the two records, and then compare the second record And the keyword of the third record, and so on, until the position of the keyword of the n-1th record and the nth record is compared. The above process is the first bubble sorting, and the result is that the record with the largest key is swapped to the position of the nth record. Then the second bubble sorting is performed, and the same operation is performed on the first n-1 records. As a result, the record with the second largest key is swapped to the position of the n-1th record. At most n-1 times, all records are arranged in order. If there is no element exchange processing at adjacent positions in a bubble sorting process, the sorting process can be ended.

Bubble sort diagram 1
Bubble sort diagram 2

3. Simple selection sort

The basic method for simple selection and sorting of n records is to select the record with the smallest key from n-i+1 records by comparing ni (1<=i<=n) among secondary keywords, and Exchange with the i-th record. When i is equal to n, all records are arranged in order.

Simple selection sorting diagram

void SelectSort(int data[],int n)
/*将数组data中的n个整数按非递减有序的方式进行排序*/
{ 
int i,j,k,tmp;
for(i=0;i<n-1;i++){
  k=i;
  for(j=i+1;j<n;j++)  /*找出最小关键字的下标*/
    if(data[j]<data[k])
      k=j;
    if(k!=i){
      tmp=data[i];
      data[i]=data[k];
      data[k]=tmp;
    }
  }
}

4. Hill sort

Hill sorting is also called "reducing incremental sorting", which is an improvement of the direct insertion sorting method.
The basic idea of ​​Hill sorting is: first divide the entire sequence of records to be sorted into several sub-sequences, and then perform direct insertion sorting respectively. When the records in the entire sequence are basically in order, then perform a direct insertion sorting on all records. The specific method is: first take an integer d1 less than n as the first increment, divide all the records of the file into d1 groups, that is, put all the records whose distance is a multiple of d1 into the same group, and proceed in each group Insert the sort directly; then take the second increment d2 (d2<d1), repeat the above grouping and sorting work, and so on, until the taken increment di=1 (di<di-1<...d2<d1) , That is, all records are placed in the same group for direct insertion sort.

Hill sorting diagram

void ShellSort(int data[],int n)
{int *delta,k,i,t,dk,j;
 k=n;
 /*从k=n开始,重复k=k/2运算,直到k=1,所得k值的序列作为增量序列存入delta*/
 i=0;
 do{
   k=k/2;
   delta[i++]=k;
 }while(k>1);
 i=0;
 while((dk=delta[i])>0){
   for(k=delta[i];k<n;++k)
     if(data[k]<data[k-dk]){  /*将元素data[k]插入到有序增量子表中*/
       t=data[k];             /*备份待插入的元素,空出一个元素位置*/
       for(j=k-dk;j>=0 && t<data[j];j-=dk)
         data[j+dk]=data[j];  /*寻找插入位置的同时元素后移*/
       data[j+dk]=t;          /*找到插入位置,插入元素*/
     }
   ++i;                       /*取下一个增量值*/
 }
}

5. Merge Sort

The so-called "merging" refers to the merging of two or more ordered documents into a new ordered document. One way to implement merge sort is to treat an unordered file with n records as a file composed of n ordered sub-files of length 1, and then merge pairwise to obtain n/2 of length 2 Or an ordered file of 1, and then merge two by two, and repeat, until the final ordered file containing n records is formed. This sorting method of repeatedly merging two ordered files into one ordered file is called two-way merge sorting.

The core operation of two-way merge sort is to merge two adjacent ordered sequences in a one-dimensional array into an ordered sequence.

Merge sort diagram

void Merge(int data[],int s,int m,int n){
/*将分别有序的data[s..m]和data[m+1..n]归并为有序的data[s..n]*/
int i,start=s,k=0;
int *temp;
temp=(int *)malloc((n-s+1)*sizeof(int));  /*辅助空间*/
for(i=m+1;s<=m && i<=n;++k)               /*将data[s..m]与data[m+1..n]归并后存入temp*/
  if(data[s]<data[i])
    temp[k]=data[s++];
    else temp[k]=data[i++];
for(;s<=m;++k)                           /*将剩余的data[s..m]复制到temp*/
    temp[k]=data[s++];
for(i=0;i<k;i++)
    data[start++]=temp[i];
free(temp);
}
void MSort(int data[],int s,int t){  /*对data[s..t]进行归并排序*/
{
int m;
if(s<t){                            /*将data[s..t]均分为data[s..m]和data[m+1..t]*/
  m=(s+t)/2;
  MSort(data,s,m);                 /*递归地对data[s..m]进行归并排序*/
  MSort(data,m+1,t);               /*递归地对data[m+1..t]进行归并排序*/
  Merge(data,s,m,t);               /*将data[s..m]和data[m+1..t]归并为data[s..t]*/
  }
}

6. Quick Sort

The basic idea of ​​quick sorting is: divide the records to be sorted into two independent parts, called the first half area and the second half area, through a sorting pass. The key of the record in the first half area is not greater than the key of the second half area. Words, and then continue to quickly sort the two parts of the records separately, so that the entire sequence is ordered.
The process of a quick sort is called a division. The specific method is to attach two position indicator variables i and j, their initial values ​​point to the first record and the last record of the sequence respectively. Suppose the key of the pivot record (usually the first record) is pivot, then first search backward from the position pointed to by j, and move the record backward to the position j when the first record with a key less than pivot is found Refer to the position, repeat the process until i and j are equal.

Quick sort diagram

int partition(int data[],int low,int high)
/*用date[low]作为枢轴元素pivot进行划分*/
/*使得data[low..i-1]均不大于pivot,data[i+1..high]均不小于pivot*/
{int i,j;
int pivot;
pivot=data[low];
i=low; j=hight;
while(i<j){          /*从数组的两端交替向中间扫描*/
  while(i<j && data[j]>=pivot)
    j--;
  data[i]=data[j];  /*比枢轴元素小者往前移*/
  while(i<j && data[i]<=pivot)
    i++;
  data[j]=data[i];  /*比枢轴元素大者往后移*/
  }
data[i]=pivot;
return i;
}
void quickSort(int data[],int low,int high)
/*用快速排序方法对数组元素data[low..high]作非递减排序*/
{
if(low<high){
  int loc=partition(data,low,high)      /*进行划分*/
  quickSort(data,low,loc-1);            /*对前半区进行快速排序*/
  quickSort(data,loc+1,high);           /*对后半区进行快速排序*/
  }
}

7. Heap Sort

The idea of ​​heap sorting: For a group of keywords to be sorted, first arrange them in a sequence according to the definition of the heap (that is, establish the initial heap), so that the largest keyword at the top of the heap (for a large root heap) can be output, and then The remaining keywords are adjusted to a new pile, and the next largest keyword is obtained, and so on, until all keywords are arranged in an orderly sequence.
The method of establishing the initial heap is to place the keywords to be sorted into the nodes of a complete binary tree (at this time, the complete binary tree does not necessarily have the characteristics of a heap). Obviously, all i>(n/2) The node Ki has no child nodes. The subtree rooted at such Ki is already a heap, so the initial heap can be built from the i-th (i=(n/2)) node Ki of the complete binary tree. , Gradually make the subtree rooted at K(n/2), K(n/2)-1, K(n/2)-2,..., K2, K1 meet the definition of heap.
In the process of building a heap for the subtree rooted at Ki, it may be necessary to exchange the values ​​of Ki and K2i (or K2i+1). As a result, the subtree rooted at K2i (or K2i+1) may no longer satisfy The definition of a pile should continue to be adjusted with K2i (or K2i+1) as the root, and iteratively in this way, it may extend to the leaf node. This method is like sifting, filtering out the largest (or smallest) keywords layer by layer, and finally outputting the largest (or smallest) element at the top of the heap.

Original sequence Original sequence
Build initial heap (large root heap)
The establishment of the initial heap (large root heap) diagram 1
The establishment of the initial heap (large root heap) diagram 2
Heap sort diagram

void HeapAdjust(int data[],int s,int m)
/*在data[s..m]所构成的一个元素序列中,除了data[s]外,其余元素均满足大根堆的定义*/
/*调整元素data[s]的位置,使data[s..m]成为一个大根堆*/
{
int tmp,j;
tmp=data[s];                 /*备份元素data[s],为其找到适当位置后再插入*/
for(j=2*s+1;j<=m;j=j*2+1){   /*沿值较大的孩子结点想下筛选*/
  if(j<m && data[j]<data[j+1])
    ++j;                     /*j是值较大的元素的下标*/
  if(tmp>=data[j])
    break;
  data[s]=data[j];  s=j;     /*用s记录待插入元素的位置(下标)*/
  }
data[s]=tmp;                 /*将备份元素插入由s所指出的插入位置*/
}
void HeapSort(int data[],int n)
/*数组data[0..n-1]中的n个元素进行堆排序*/
{
  int i;  int tmp;
  for(i=n/2;i>=0;--i)        /*将data[0..n-1]调整为大根堆*/
    HeapAdjust(data,i,n-1);
  for(i=n-1;j>0;--i)
  {
    tmp=data[0];  data[0]=data[i];
    data[i]=tmp;             /*堆顶元素data[0]与序列末的元素data[i]交换*/
    HeapAdjust(data,0,i-1);  /*待排元素的个数减一,将data[0..i-1]重新调整为大根堆*/
  }
}

8. Summary of internal sorting methods

Sorting method time complexity Auxiliary space stability
Insert directly O (n²) O (1) stable
Simple choice O (n²) O (1) Unstable
Bubble Sort O (n²) O (1) stable
Hill sort O (n ^ 1.3) O (1) Unstable
Quick sort O (nlogn) Log in Unstable
Heap sort O (nlogn) O (1) Unstable
Merge sort O (nlogn) O (n) stable

Guess you like

Origin blog.csdn.net/Doigt_/article/details/108606501