编程算法 - 把数组排成最小的数 代码(C)

把数组排成最小的数 代码(C)

 

本文地址: http://blog.csdn.net/caroline_wendy

 

题目: 输入一个正整数数组, 把数组里所有数字拼接起来排成一个数, 打印能拼接出的所有数字中最小的一个.

 

大数转换为字符串, 重载快速排序比较方法, 进行排序, 最后拼接.

 

代码:

 

/*
 * main.cpp
 *
 *  Created on: 2014.6.12
 *      Author: Spike
 */

/*eclipse cdt, gcc 4.8.1*/

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int compare(const void* strNumber1, const void* strNumber2) {
	const int MaxNumberLength = 10;
	char* strCombine1 = new char[MaxNumberLength*2 + 1];
	char* strCombine2 = new char[MaxNumberLength*2 + 1];

	strcpy(strCombine1, *(const char**)strNumber1);
	strcat(strCombine1, *(const char**)strNumber2);

	strcpy(strCombine2, *(const char**)strNumber2);
	strcat(strCombine2, *(const char**)strNumber1);

	int result = strcmp(strCombine1, strCombine2);

	delete[] strCombine1;
	delete[] strCombine2;

	return result;
}

void PrintMinNumber (int* numbers, int length) {
	const int MaxNumberLength = 10;
	if (numbers == NULL || length <= 0)
		return;
	char** strNumbers = (char**)(new int[length]);
	for (int i=0; i<length; ++i) {
		strNumbers[i] = new char[MaxNumberLength + 1];
		sprintf(strNumbers[i], "%d", numbers[i]);
	}
	qsort(strNumbers, length, sizeof(char*), compare);

	for (int i=0; i<length; ++i)
		printf("%s", strNumbers[i]);
	printf("\n");

	for (int i=0; i<length; ++i)
		delete[] strNumbers[i];
	delete[] strNumbers;
}

int main(void)
{
    int input[] =  {3, 32, 321};
    PrintMinNumber(input, 3);

    return 0;
}

 

 

 

 

 

输出:

 

321323

 

 

 

 

 

 

 

 

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

ElminsterAumar

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值