Bubble sort positive and reverse order example

C language positive and reverse order bubbling


They all arrange irregular arrays from small to large;
positive ordering means traversing from left to right;
reverse ordering means traversing from right to left.

Positive sequence bubbling

void bubbleSort1(int arr[],int size) {
    
    //顺序
	for (int a = 0; a < size-1; a++){
    
    //最多size-1轮比较
		for (int b = 0; b < size - 1 - a; b++){
    
    
			if (arr[b ]>arr[b+1]){
    
    
				int c = arr[b ];
				arr[b] = arr[b+1];
				arr[b+1] = c;
			}
		}
	}	
}

Element isRight to leftTo determine in turn. Each cycle selects the currentThe biggest one is on the right
Insert picture description here

Reverse bubbling

void bubbleSort2(int arr[], int size) {
    
    //逆序
	for (int a = 0; a < size-1; a++) {
    
    
		for (int b = size - 1; b > a; b--) {
    
    
			if (arr[b - 1] > arr[b]) {
    
    
				int tmp = arr[b - 1];
				arr[b - 1] = arr[b];
				arr[b] = tmp;
			}
		}
	}
}

Element is fromLeft to rightTo determine in turn. Each cycle selects the currentThe smallest on the left

Insert picture description here

Source code

Mainly to distinguish the difference between the two traversals, their change process is also different

#include <stdio.h>
#include <stdlib.h>
#pragma warning (disable:4996)

void bubbleSort1(int arr[],int size) {
    
    //顺序
	for (int a = 0; a < size-1; a++){
    
    //最多size-1轮比较
		for (int b = 0; b < size - 1 - a; b++){
    
    
			if (arr[b ]>arr[b+1]){
    
    
				int c = arr[b ];
				arr[b] = arr[b+1];
				arr[b+1] = c;
			}
		}
	}	
}

void bubbleSort2(int arr[], int size) {
    
    //逆序
	for (int a = 0; a < size-1; a++) {
    
    //最多size-1轮比较
		for (int b = size - 1; b > a; b--) {
    
    
			if (arr[b - 1] > arr[b]) {
    
    
				int tmp = arr[b - 1];
				arr[b - 1] = arr[b];
				arr[b] = tmp;
			}
		}
	}
}
int main(){
    
    
	int arr[] = {
    
     2, 5, 8, 3 ,7, 9};
	bubbleSort2(arr,sizeof(arr)/sizeof (arr[0]));
	//直接改变函数名即可。
	for (int a = 0; a < sizeof(arr) / sizeof (arr[0]); a++){
    
    
		printf(" %d", arr[a]);
		//2 5 8 3 7 9--2 3 5 7 8 9;
	}
	system("pause");
	return 0;
}

The two results are as shown in the figure:
Insert picture description here

Guess you like

Origin blog.csdn.net/zhaocx111222333/article/details/109449584
Recommended