Simple sort (bubble sort, selection sort, insertion sort)#C++

Simple sorting (bubble sorting, selection sorting, insertion sorting)

"Example: Program to receive several integers input by the keyboard, and output from small to large after sorting. First input an integer n, indicating that there are n integers to be sorted, and then input n integers to be sorted".

(1) Selection sort (O(n^2))

If there are N elements to be sorted, first find the smallest one (called the 0th smallest) from the N elements and place it on the 0th position (exchange positions with the original 0th position element), and then Then find the smallest element from the remaining N-1 elements and place it on the first position, and then find the smallest element from the remaining N-2 elements and place it on the second position...until all elements All in place.

Code

void SelectionSort(int a[], int size){
    
    
	for(int i=0; i<size-1; i++){
    
    	//每次循环后将第i小的元素放好 
		int tmpMin = i;
		//用来记录从第i个到第size-1个元素中,最小的那个元素的下标 
		for(int j = i+1; j<size; j++){
    
    
			if(a[j] < a[tmpMin])
				tmpMin = j;
		}
		//下面将第i小的元素放在第i个位置上,并将原来站着第i个位子的元素挪到后面
		int tmp = a[i];
		a[i] = a[tmpMin];
		a[tmpMin] = tmp; 
	}
}	

(2) Insertion sort (O(n^2))

  1. Divide the entire array ainto two parts, an ordered part and an unordered part. The former is on the left and the latter is on the right. Only the first part a[0]is in order, and the rest belong to the disordered part.
  2. Take the first (leftmost) element of the unordered part each time and add it to the ordered part. Assuming that it is inserted in a suitable position p, the original pposition and the ordered part of the elements after it are moved one place to the right. The ordered part adds an element.
  3. Until the disordered part has no elements

Code

void InsertionSort(int a[], int size){
    
    
	for(int i = 1; i < size; i++){
    
    
		//a[i]是无序元素中最左的,每次循环将a[i]放到合适位置
		for(int j = 0; j < i; j++){
    
    
			if( a[j] > a[i]){
    
    
				//要把a[i]放到位置j,原下标j到i-1的元素都往后移一个位置 
				int tmp = a[i];
				for(int k = i; k > j; k--)
					a[k] = a[k-1];
				a[j] = tmp;
				break;
			}
		} 
	}
}	

(3) Bubble sort (O(n^2))

The big element keeps floating up like bubbles in the water, moving to the right

Code

void BubbleSort(int a[], int size){
    
    
	for(int i = size-1; i>0; i--){
    
    
		//每次要将未排序部分的最大值移动到下标i的位置
		for(int j = 0; j < i; j++)
			if( a[j] > a[j+1]) {
    
    
				int tmp = a[j];
				a[j] = a[j+1];
				a[j+1] = tmp;
			}
	}
}

Guess you like

Origin blog.csdn.net/qq_44524918/article/details/108856440