Primary optimization of bubble sorting method (C language &&C++)

The overall idea of ​​bubbling sorting:
Insert picture description here
Insert picture description here
sorting optimization: when the bubbling sorting is completed, no exchange occurs, at this time we can directly end the loop to improve the efficiency of the algorithm;
C language version:

#include <stdio.h>

void BubbleSort() {
    
    
	int a[5],i=0,j=0,flag=0,t=0;
	for (i = 0; i < 5; i++)  //数组输入
		scanf("%d", &a[i]);
	
	for (i = 0; i < 4; i++) {
    
    
		flag = 0;
		for(j=0; j< 5-i ;j++)
			if (a[j - 1] > a[j]) {
    
    
				t = a[j - 1];
				a[j - 1] = a[j];
				a[j] = t;
				flag = 1;   //一旦发生交换,将flag置1
			}
		if (flag == 0)
			break;//说明没有发生交换,跳出循环
	}
	for (i = 0; i < 5; i++)
		printf("%d ",a[i]);
}

int main() {
    
    
	BubbleSort();
	return 0;
}

Try to use C++ to write a sorting class, which can satisfy other types of array sorting at the same time:

#include <iostream>
#include <vector>
#include <string>
using namespace std;

class Sort {
    
    
	friend int main(); //友元函数访问私有变量
	friend void test1();
	friend void test2();
	friend void test3();
	template<class T>
	void BubbleSort(T* vec,int n) {
    
    
		int flag = 0;//标记法判断是否发生 交换
		for (int i = n; i > 1; i--)
		{
    
    //一共i个数进行排序
			for (int j = 0; j < i - 1; j++)
			{
    
    
				if (vec[j] > vec[j + 1])
				{
    
    
					swap<T>(vec[j], vec[j + 1]);
					flag = 1;  //发生交换才将flag置1
				}
			}
			if (flag == 0) //一整趟下来没发生交换,说明无需继续排序,跳出循环
				break;
		}
	}
	template<class T>
	void swap(T& a, T& b) //交换函数
	{
    
    
		a = a + b;
		b = a - b;
		a = a - b;
	}

	template<class T>
	 void printVec(T* vec, int n) //打印输出数组
	{
    
    
		 for (int i = 0; i < n; i++)
			 cout << vec[i] << " ";
	}
};

void test1()//测试整型数组
{
    
    
	int a[6] = {
    
     30,20,50,10,60,40 };
	int n = sizeof(a) / sizeof(int);
	Sort s;
	s.BubbleSort<int>(a, n);
	s.printVec(a, n);
}

void test2()//测试字符数组
{
    
    
	Sort bubsor;
	char c[] = "gfedcba";
	int n = strlen(c);
	bubsor.BubbleSort<char>(c,n);
	bubsor.printVec<char>(c, n);
}

void test3()//测试浮点数组
{
    
    
	double a[6] = {
    
     10.2432,60.8843,40.0921,50.2134,20.1234,10.4216 };
	int n = sizeof(a) / sizeof(double);
	Sort s;
	s.BubbleSort(a, n);
	s.printVec(a, n);
}
int main() {
    
    
	cout << "字符数组冒泡排序:" << endl;
	test2();
	cout << endl;
	cout << endl << "int数组冒泡排序:" << endl;
	test1();
	cout << endl;
	cout << endl << "double数组冒泡排序:" << endl;
	test3();
	cout << endl;
	return 0;
}

Guess you like

Origin blog.csdn.net/Genius_bin/article/details/112728952