无限制数字(仅仅int类型)的大小的自然排序算法

直接上代码:

#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
#include <cctype>

// Function to compare two strings in a natural way
bool naturalCompare(const std::string& a, const std::string& b) {
	size_t i = 0, j = 0;
	while (i < a.size() && j < b.size()) {
		// Skip leading zeros in numbers
		if (std::isdigit(a[i]) && std::isdigit(b[j])){
			size_t valA = 0, valB = 0;
			std::string strA {};
			std::string strB {};
			while(i < a.length() && std::isdigit(a[i])) {
				valA += (a[i] -'0');
				if(valA != 0) {
					strA.push_back(a[i]);
				}
				i++;
			}
			while(j < b.length() && std::isdigit(b[j])) {
				valB += (b[j] -'0');
				if(valB != 0) {
					strB.push_back(b[j]);
				}
				j++;
			}

			if(strA != strB && strA.size() == strB.size()) {
				return strA <strB;
			}
			if(strA != strB && strA.size() != strB.size()) {
				return strA.size() <strB.size();
			}
		} else {
			// Compare characters if not both are digits
			if (a[i] != b[j]) {
				return a[i] < b[j];
			}
			++i;
			++j;
		}
	}

	// If we reach the end of one of the strings
	return a.size() < b.size();
}

int main() {
	std::vector<std::string> vec = {"b3", "", "file1.txt", "file20.txt",
									"fi.txt","a","15","C10",
									"c00013A","c0013A","c00000013A","00000013A",
									"","   ","&&&__","$%^&*()()++",
									"99999999999999999999999999999999999999999","9999999999999999999999aaa9999999999999999999","9999999999999999999999AAA9999999999999999999",
									"a_123456789123456789abc","a_123456789123456789bbc",
									"bcm123bbc445","bcm123bbc4","bcm123bbc4451","bcm123bbc445kk"};

	// Sort the vector using the naturalCompare function
	std::sort(vec.begin(), vec.end(), naturalCompare);

	// Print the sorted vector
	for (const auto& str : vec) {
		std::cout << str << std::endl;
	}

	return 0;
}

代码说明:

        .数字和字符分开

                判断是否是数字

                        将a的数字提取到strA,(不加入前缀0,但是中间的0需要)

                        将b的数字提取到strB

                        比较strA和strB是否相等 && strA和strB的size是否相等(不相等,而且位数也不相等)

                                按照位数(size)排序

                        比较strA和strB是否相等 && strA和strB的size是否相等(不相等,而且位数相等)

                                按照字母顺序表排序

                是字符:

                        按照字母顺序表进行排序。

测试结果:

  • 3
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值