Understand insertion sort and selection sort in seconds

Insertion sort principle: It works by constructing an ordered sequence, for unsorted data, scan from back to front in the sorted sequence, find the corresponding position and insert.

Insertion sorting core: Assuming that the first element is arranged, the elements after the arrangement are compared from the back to the front and moved one by one.

Insertion sort implementation:

 

  1. void insertion_sort(int a[], int n)  
  2. {  
  3.     int i,j,tmp;  
  4.     for (i = 1; i < n; i++) {  
  5.         tmp = a[i];  
  6.         for (j = i - 1; j >= 0 && a[j] > tmp; j--) {  
  7.             a[j+1] = a[j];  
  8.         }  
  9.         a[j+1] = tmp;  
  10.     }  
  11. }  
void insertion_sort(int a[], int n)
{
	int i,j,tmp;
	for (i = 1; i < n; i++) {
		tmp = a[i];
		for (j = i - 1; j >= 0 && a[j] > tmp; j--) {
			a[j+1] = a[j];
		}
		a[j+1] = tmp;
	}
}

Insertion sort process animation:



Selection sort:

 

Similar to selection sort and insertion sort, both are in-place comparison sorts.

 

The core idea of ​​selection sorting: the first part of the unsorted part is taken as the smallest (largest), and then compared with the rest in turn, if there is a smaller (larger), write down the subscript and use this as the new smallest (maximum) value, continue to compare, after one pass, then swap with the first one.

 

Selection sort implementation:

 

  1. void selection_sort(int a[], int n)  
  2. {  
  3.     int i, j, k;  
  4.     for (i = 0; i< n-1; i++) {  
  5.         k = i;  
  6.         for (j = i+1; j < n; j++) {  
  7.             if (a[k] > a[j])  
  8.                 k = j;  
  9.         }  
  10.         if (k != i) {  
  11.             int tmp = a[i];  
  12.             a[i] = a[k];  
  13.             a[k] = tmp;  
  14.         }  
  15.     }  
  16. }  
void selection_sort(int a[], int n)
{
	int i, j, k;
	for (i = 0; i< n-1; i++) {
		k = i;
		for (j = i+1; j < n; j++) {
			if (a[k] > a[j])
				k = j;
		}
		if (k != i) {
			int tmp = a[i];
			a[i] = a[k];
			a[k] = tmp;
		}
	}
}

Selection sort process animation:

 

 

 

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326395193&siteId=291194637